Skip to content

Iterate over a Literal Sequence

Problem

A loop needs to visit a fixed sequence of values, and declaring a collection variable only to iterate over it once adds noise.

Solution

Write the sequence as an aggregate literal directly in the foreach header. A map literal works as well; its keys are bound to the index_identifier.

1
2
3
4
array<int, 4> sequenceArray = {2, 4, 6, 8};
foreach (i : sequenceArray[j]) {
    (void) printf(i);   //  i: 2 -> 4 -> 6 -> 8
}
1
2
3
4
foreach (i : {2, 4, 6, 8}[j]) {
    (void) printf(i);   //  i: 2 -> 4 -> 6 -> 8
    (void) printf(j);   //  j: 0 -> 1 -> 2 -> 3
}
1
2
3
4
foreach (i : {"A":10, "B":11, "C":12, "D":13, "E":14, "F":15}[j]) {
    (void) printf(i);   //  i: 10  -> 11  -> 12  -> 13  -> 14  -> 15
    (void) printf(j);   //  j: "A" -> "B" -> "C" -> "D" -> "E" -> "F"
}

See also