Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this work in c++? [duplicate]

Tags:

c++

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

like image 796
johnyka Avatar asked Feb 28 '26 21:02

johnyka


2 Answers

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)

like image 133
Sajad Karuthedath Avatar answered Mar 03 '26 11:03

Sajad Karuthedath


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 :)

like image 27
michael60612 Avatar answered Mar 03 '26 12:03

michael60612