-2

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
  • 1
    My C++ is a bit old now, but this (a,b,x,y) doesn't make much sense here. It may only evaluate the last item y which is 0 and therefore falsy. What did you expect this to do? Jan 23, 2015 at 8:50
  • (<flashy thing> Forget about the semicolons. I was confusing if with for.) You're abusing the comma operator, and it's yielding a true value. Jan 23, 2015 at 9:02
  • 2
    Just because it compiles doesn't mean it makes sense. Also the compiler actually gives you a warning about this: warning: left operand of comma operator has no effect Jan 23, 2015 at 9:04
  • 1
    @thorstenmuller if you are a beginner programmer then you code "for loop" to print 10 numbers which is also doesn't make any sense but its just for a practice. So I am practicing ..
    – anaszaman
    Jan 23, 2015 at 9:06
  • 3
    I'm voting to close this question as off-topic because it is about an implementation issue.
    – user53019
    Jan 23, 2015 at 14:53

1 Answer 1

12

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.