Skip to content

Multi-Assignment

Parallel Assignment

Multiple variables can be assigned simultaneously. All right-hand side values are evaluated before any assignment occurs:

int x = 10;
int y = 20;
x, y = y, x; // x=20, y=10

Three-Way Rotation

int a = 1;
int b = 2;
int c = 3;
a, b, c = b, c, a; // a=2, b=3, c=1

Expressions on the Right Side

int x = 5;
int y = 10;
x, y = y + 1, x * 2; // x=11, y=10

Multi-Typed Declaration

Declare multiple variables of different types in one statement:

int x, float y = 1, 6.5;
int a, float b, int c = 10, 2.5, 30;

Move and Copy Semantics

For custom types, use move or copy modifiers:

Handle a;
Handle b;
a, b = move b, move a;
a, b = copy b, copy a;

Built-in swap()

The swap() builtin swaps two variables of the same type:

int x = 1;
int y = 2;
swap(x, y); // x=2, y=1
// Works with any same-typed values
Point p1;
Point p2;
swap(p1, p2);

Both operands must be the same type:

int x = 1;
float y = 2.0;
// swap(x, y); // ERROR: same type required