Jay M. Jay M. - 3 months ago 64
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;


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.