[Solved] What does an “extra” semicolon means? [duplicate]


A for loop is often written

int i;
for (i = 0; i < 6; i++) {
    ...
}

Before the first semicolon, there is code that is run once, before the loop starts. By omitting this, you just have nothing happen before the loop starts.

Between the semicolons, there is the condition that is checked after every loop, and the for loop end if this evaluates to false. By omitting this, you have no check, and it always continues.

After the second semicolon is code that is run after every cycle, before that condition is evaluated. Omitting this just runs additional code at that time.

The semicolons are always there, there is nothing special about the face that they are adjacent. You could replace that with

for ( ; ; )

and have the same effect.

While for (;;) itself does not return true (It doesn’t return anything), the second field in the parentheses of the for always causes the loop to continue if it is empty. There’s no reason for this other than that someone thought it would be convenient. See https://stackoverflow.com/a/13147054/5567382. It states that an empty condition is always replaced by a non-zero constant, which is the case where the loop continues.

As for size and efficiency, it may vary depending on the compiler, but I don’t see any reason that one would be more efficient than the other, though it’s really up to the compiler. It could be that a compiler would allow the program to evaluate as non-zero a constant in the condition of a while loop, but recognise an empty for loop condition and skip comparison, though I would expect the compiler to optimize the while loop better. (A long way of saying that I don’t know, but it depends on a lot.)

2

solved What does an “extra” semicolon means? [duplicate]