Jay M. Jay M. - 1 year ago 131
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download