Skip to content

For Loop Statement

IsaacShelton edited this page Mar 21, 2022 · 1 revision

For Loop

For loops are used for precise control over looping

Common syntax

for(i usize = 0; i < count; i++)   // ...
for(i usize = 0; i < count; i++),  // ...
for(i usize = 0; i < count; i++)   { /* ... */ }

Alternative syntax options

for i usize = 0; i < count; i++    // ...
for i usize = 0; i < count; i++,   // ...
for i usize = 0; i < count; i++    { /* ... */ }
for(i: usize = 0; i < count; i++)  // ...
for(i: usize = 0; i < count; i++), // ...
for(i: usize = 0; i < count; i++), { /* ... */ }

The statement join operator is not allowed inside of the head of a for loop, instead ; is used to separate the different portions of the for loop's header.

Break and Continue

Both break and continue apply to for loops

Loop Labels

Loop labels can be used for a for loop by specifying a name for the loop label followed by : before after for

for counting_to_ten : (i usize = 0; i < 10; i++) {
    if i == 6, break counting_to_ten
}

Because of the syntax for loop labels, it is not possible to neglect parentheses when using : Type syntax.

Clone this wiki locally