Aresloom Aresloom - 1 month ago 10
C++ Question

Why does variable declaration work well as the condition of for loop?

What's the return value/type of a declaration like

int i = 5
?

Why doesn't compile this code:

#include <iostream>

void foo(void) {
std::cout << "Hello";
}

int main()
{
int i = 0;
for(foo(); (int i = 5)==5 ; ++i)std::cout << i;
}


while this does

#include <iostream>

void foo(void) {
std::cout << "Hello";
}

int main()
{
int i = 0;
for(foo(); int i = 5; ++i)std::cout << i;
}

Answer

The for loop requires condition to be either an expression or a declaration:

condition - either

  • an expression which is contextually convertible to bool. This expression is evaluated before each iteration, and if it yields false, the loop is exited.
  • a declaration of a single variable with a brace-or-equals initializer. the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.

The 1st code doesn't work because (int i = 5)==5 is not a valid expression at all. (It's not a declaration either.) The operand of operator== is supposed to be an expression too, but int i = 5 is a declaration, not an expression.

The 2nd code works because int i = 5 matches the 2nd valid case for condition; a declaration of a single variable with a equals initializer. The value of i will be converted to bool for judgement; which is always 5, then leads to an infinite loop.

Comments