Jay M. Jay M. - 29 days ago 12
C++ Question

Unexpected behaviour in a for loop

Why does this compile, but not work?

for(a,b=0; a,b != 55; a,b++)
{
//outputs garbage
std::cout << "a = " << a << std::endl;
//outputs expected results
std::cout << "b = " << b << std::endl;
}

Answer

The comma operator says execute the statement on the left then execute the statement on the right:

  a, b=0

first executes the statement a which does nothing, then it executes b=0 which assigns zero to b.

Comments