I am a little bit confused about this code. Why does the else block get executed?
Please explain it.
int a=10,b=20;
char x=1,y=0;
if(a,b,x,y){
cout << "A" << endl;
}else{
cout << "B" << endl;
}
9
According to this Wiki Page:
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).
So this: if(a,b,x,y){
will only take the value of y
into consideration for the actual if
part, which has a value of 0
which would evaluate to false
, thus causing the else
part of your code to execute.
EDIT: That being said, the code you posted does not make much sense. The comma operator will evaluate and discard the result (other than the last item). This would be helpful if you would need to chain a series of methods which depend on each other and decide what to do by using the result of the last one.
0