-3

This compiles and runs, but produces garbage values for "a". Why doesn't "a" increment like "b"? Why is it producing garbage?

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;
}
Semaphore
  • 63
  • 1
  • 12
  • 3
    you need to study c++ syntax -- in particular the comma operator doesn't do what you think it does. – Dale Wilson Nov 02 '16 at 21:17
  • Of course it works! However, it may work in a way different from what you expected. How do you expect the program to work? – CiaPan Nov 02 '16 at 21:18
  • 1
    works for me, what output are you expecting? – DaveB Nov 02 '16 at 21:21
  • @DaveB To be pedantic, it doesn't work for you since as written it contains undefined behavior. the `a` variable is uninitialized. – Dale Wilson Nov 02 '16 at 21:22
  • Because it is equivalent to `for(b=0; b != 55; b++)`. – molbdnilo Nov 02 '16 at 21:23
  • 1
    @DaleWilson good point, I should have said I get the output I expected. – DaveB Nov 02 '16 at 21:27
  • Seems the OP needs to define "doesn't work" -- not really clear what is expected here; are they expecting the `a` variable to magically define itself? -- to magically increment itself? -- (Because as defined, the program says that `a` outputs garbage, and that's exactly what it does, and it's exactly what you would expect it to do -- so, the OP will need to define their expected behavior a little better.) – BrainSlugs83 Nov 02 '16 at 21:33
  • I expected to see both variables to be incremented. – Semaphore Nov 02 '16 at 21:43
  • I changed it to be more specific. – Semaphore Nov 02 '16 at 21:53
  • @BrainSlugs83 Respectively, If I understood it, I wouldn't need to have asked it, the previous comments covered what needed to be asked and to me it seems like that was a bit much. – Semaphore Nov 02 '16 at 21:57

1 Answers1

5

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

  a, b=0

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

Why does the comma operator exist? The comma operator can be useful when the expressions have side effects.

It also serves a sequence point which tell the compiler "everything on the left must be complete before anything on the right happens. This constrains the optimizations allowed by the compiler, so for example a += 1, b = a + c[a] will always add one to a before using it as an index. Something like b = ++a + c[a] is undefined because the compiler can increment a before or after it uses it as an index.

Dale Wilson
  • 9,166
  • 3
  • 34
  • 52