Skip to content

Control Flow

Derek Snider edited this page May 19, 2026 · 1 revision

Control Flow

if / else

if (x > 0) {
    cout << "positive" << endl;
} else if (x == 0) {
    cout << "zero" << endl;
} else {
    cout << "negative" << endl;
}

for

for (int i = 0; i < 10; i++) {
    cout << i << endl;
}

Typed comma declarations are supported:

for (int i = 0, j = 10; i < j; i++, j--) {
    cout << i << " " << j << endl;
}

while / do-while

while (x > 0) {
    x--;
}

do {
    x++;
} while (x < 100);

Range-based for

C++ style iteration over arrays:

array names;
php::array_push(names, "Alice");
php::array_push(names, "Bob");

for (string name : names) {
    cout << name << endl;
}

Works with string and int element types. See Modern Features.

switch / case / default

switch (x) {
    case 1:
        cout << "one" << endl;
        break;
    case 2:
        cout << "two" << endl;
        break;
    default:
        cout << "other" << endl;
        break;
}

Case values must be literal constants (integers or character literals). Fall-through occurs between cases unless break is used — same as C.

rust::match

A no-fall-through alternative to switch, modeled after Rust's match:

rust::match (x) {
    1 => cout << "one" << endl;
    2 | 3 => cout << "two or three" << endl;
    _ => cout << "other" << endl;
}
  • Patterns are integer constants; | separates OR-alternatives
  • _ is the wildcard (like default)
  • No fall-through — each arm is independent
  • Use { } blocks for multi-statement arms
  • The rust:: prefix is required

The wildcard arm can appear anywhere — explicit patterns always take precedence:

rust::match (n) {
    _  => result = -1;     // wildcard listed first
    10 => result = 999;    // still wins for n == 10
}

Ternary operator

int y = (x > 0) ? x : -x;

Works in assignments and return statements. Both branches must produce the same type.

What's next?

Clone this wiki locally