3

I ran into a situation like this:

if(true,false)
{
    cout<<"A";
}
else
{
    cout<<"B";
}

Actually it writes out B. How does this statement works? Accordint to my observation always the last value counts. But then what is the point of this?

Thanks

johnyka
  • 399
  • 3
  • 15

3 Answers3

3

from http://www.cplusplus.com/doc/tutorial/operators/

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the right-most expression is considered.

For example, the following code: a = (b=3, b+2);

would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3.

So here

if(true,false)
{

}

evaluates to if(false)

Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49
2

The comma operator will run whatever is on the left side of the comma, discard it, and then run whatever is on the right side of the operator. In this case:

if (true, false)

will always be equivalent to if (false), so it will never run the if condition, and will always run the else condition.

As a side note: Never write code like this. It is serving no purpose but to obfuscate the code.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42
2

According to http://www.cplusplus.com/doc/tutorial/operators/

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the right-most expression is considered.

So for example consider the following:

int a, b;
a = (b=3, b+2);

b gets set to 3, but the equals operator only cares about the second half so the actual value returned is 5. As for the usefulness? That's conditional :)

michael60612
  • 397
  • 2
  • 10
  • 2
    This is essentially the same as Sajad LFC's answer, with the difference that it doesn't point out that the example (with a and b and stuff) is not your own idea. Also, cplusplus.com is not the standard. –  Jan 06 '14 at 20:05
  • @H2CO3 He answered while I was looking up the answer apparently but you're right :) Cheers. – michael60612 Jan 06 '14 at 20:08
  • 1
    @michael60612: i answered first as provided by H2CO3 – Sajad Karuthedath Jan 06 '14 at 20:17