Aresloom Aresloom - 1 month ago 6
C++ Question

Return value of a declaration

Whats 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 brace-or-equals initializer. Note the value of i is always 5, which will lead to an infinite loop here.