-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;      
}

closed as off-topic by Kilian Foth, Bart van Ingen Schenau, GlenH7, Jan Hudec, MetaFight Jan 23 '15 at 18:34

  • This question does not appear to be about software engineering within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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? – thorsten müller Jan 23 '15 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. – Kilian Foth Jan 23 '15 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 – thorsten müller Jan 23 '15 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 .. – Tomb Jan 23 '15 at 9:06
  • 3
    I'm voting to close this question as off-topic because it is about an implementation issue. – GlenH7 Jan 23 '15 at 14:53
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.

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