0

Good day, everyone.

I've come across a peculiar piece of code today, which I don't quite understand. I don't even know how to search for this particular problem.

In this code, which works, a variable assignment is done like this:

if(condition) {
    Var1 = false, Var2 = false;
}

Now, I was under the impression, that ALL commands need to be terminated by a semicolon instead of a comma. I am familiar with the syntax

Var1 = Var2 = false;

but not with the one posted above. The compiler (g++) doesn't even throw me a warning or anything...am I missing something from the specification here? Or is the compiler generous with me and just replaces the , with a ; internally? If so, shouldn't he at least throw a warning?

Thank you for your time.

ATaylor
  • 2,598
  • 2
  • 17
  • 25

3 Answers3

1

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). (read more)

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
1

As Alexandru Barbarosie pointed out, there's quite a thorough explanation on what's happening at https://stackoverflow.com/questions/1613230/uses-of-c-comma-operator

To quickly summarize it for whomever stumbles across this post: When used outside of for loops and stuff, the , actually has the same effect as the ;.

For more information, please visit the link.

Community
  • 1
  • 1
ATaylor
  • 2,598
  • 2
  • 17
  • 25
1

am I missing something from the specification here?

Yes, it's the "comma operator", specified by C++11 5.18. It evaluates the sub-expression to the left, then the one to the right, and the overall result is that of the right-hand one.

In this case, it's equivalent to two expression statements separated by ;

It's useful in places like if/while/for where you're only allowed one expression, but might want to do more than one thing:

while (++i, --j != 0)

and also if you like to jam multiple statements together to make life difficult for whoever has to read your code.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Hmm, this one's interesting. I may be able to use it in the future. You learn something new every day. Thank you. :) – ATaylor Oct 01 '13 at 09:07
  • @ATaylor You don't want to use it (except maybe for obfuscation). Mike made that quite clear. There are very few, if any valid uses of the comma operator. – James Kanze Oct 01 '13 at 09:12
  • @JamesKanze Yeah, I came to the same conclusion by myself. Still, thank you for the heads up. – ATaylor Oct 01 '13 at 09:13