Omitting for clause elements

May 31, 2024

For statements with for clause

… Any element of the ForClause may be empty but the semicolons are required unless there is only a condition. If the condition is absent, it is equivalent to the boolean value true.

for cond { S() }    is the same as    for ; cond ; { S() }
for      { S() }    is the same as    for true     { S() }

So this goes to show that the single condition form of the for loop is really just a special case of the “for clause” for loop, with the init and post statements omitted.

But let’s look at some other examples of omitting elements of the for clause. These are all valid:

for x := 0; ; { // Initialize variable x, then start an infinite* loop
for ; x < 3; { // Same as `for x < 3 {`
for ; ; x++ { // Increments x after every iteration of the looop
for x := 0; ; x++ { // Initializes variable x, then increments it after every iteration of the infinite* loop
for ; ; { // Same as `for true {` or `for {`

*such loops can still be terminated by a terminating statement such as break or return.

Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


For statements with for clause

Today we’ll look at the second, of three, types of for statements: Those with a for clause. For statements with for clause A “for” statement with a ForClause is also controlled by its condition, but additionally it may specify an init and a post statement, such as an assignment, an increment or decrement statement. The init statement may be a short variable declaration, but the post statement must not. ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .


Iteration over strings

For statements with range clause … For a string value, the “range” clause iterates over the Unicode code points in the string starting at byte index 0. On successive iterations, the index value will be the index of the first byte of successive UTF-8-encoded code points in the string, and the second value, of type rune, will be the value of the corresponding code point. If the iteration encounters an invalid UTF-8 sequence, the second value will be 0xFFFD, the Unicode replacement character, and the next iteration will advance a single byte in the string.


Iteration over arrays and slices

For statements with range clause … For an array, pointer to array, or slice value a, the index iteration values are produced in increasing order, starting at element index 0. If at most one iteration variable is present, the range loop produces iteration values from 0 up to len(a)-1 and does not index into the array or slice itself. For a nil slice, the number of iterations is 0. From this above paragraph, we can be assured that ranging over an array, pointer to array, or slice, will operate in a defined order–from index 0, upward.

Get daily content like this in your inbox!

Subscribe