DEV Community

loading...

TIL: The smart difference between infinite for loops that work and those that break

Michele Caci
Software engineer, Gopher but very curious about every tech topic, travel & languages (programming and spoken ones)
・1 min read

Consider this Go function with an infinite for loop:

func exampleA() int {
    for {
        /* do something */
        return 1
    }
}
Enter fullscreen mode Exit fullscreen mode

Take a moment to reflect on this question: Does this code break at compilation time?

If you think: "well yes, there is a missing return before the function closes; take as example the following code where a break is introduced before the return. How could this function work?"; I would agree that your statement and example is correct and that exampleB would indeed get a missing return message from the compiler

func exampleB() int {
    for {
        break
        return 1
    }
}
Enter fullscreen mode Exit fullscreen mode

However you may very well be surprised to discover that, if you leave the function exampleA unaltered, without the missing return at the end, and test it somewhere (for example in Go's Playground it will compile and execute without complaining.

How is it possible?

An infinite for statement without a break inside is considered by the compiler as a terminating statement, a statement that is located at the end of a list of statement and that blocks the execution of any further statements within the same block.

Which means that the following example also works despite the absence of any return statement.

func exampleC() int {
    for {}
}
Enter fullscreen mode Exit fullscreen mode

The infinite for loop with no breaks is not the only terminating statement present in Go; for more details please consult this section of the golang reference spec.

Hope this was helpful, thanks a lot for your time reading it!

Discussion (0)

Forem Open with the Forem app