Reputation: 63
What is the difference between these two statements. I get different results when I use these interchangeably. I was hoping that someone could explain this for me. So whats the difference between, this...
else if ( ( elecshow ==2,3,4,5,6,8,9,10,16 ) )
and this...
else if ( ( elecshow ==2 ) || ( elecshow ==3 ) || ( elecshow ==4 ) || ( elecshow ==5 ) || ( elecshow ==6 ) || ( elecshow ==8 ) || ( elecshow ==9 ) || ( elecshow ==10 ) || ( elecshow ==16 ) )
I know this is simple stuff but your input would be appreciated.
Upvotes: 0
Views: 51
Reputation: 664406
Check what the comma operator actually does. Your first snippet is equivalent to
else if ( ((((((((elecshow ==2),3),4),5),6),8),9),10),16 )
or (if we assume that evaluating elecshow
doesn't throw etc.) just
else if ( 16 )
You will need to use the second one, although you might be able to shorten it to something like
else if (elecshow > 1 && elecshow <= 10 && elecshow != 7 || elecshow == 16)
Upvotes: 2
Reputation: 24078
The comma operator
evaluates each of its operands (from left to right) and returns the value of the last operand
Combined with the fact that ==
has higher precedence than ,
what happens here is that elecshow ==2
is evaluated, then 3
, then 4
, ... and finally 16
.
The last evaluation is returned and, 16
being a truthy value, the execution will enter the else if
.
The result differs from
else if ( ( elecshow ==2 ) || ( elecshow ==3 ) || ( elecshow ==4 ) || ( elecshow ==5 ) || ( elecshow ==6 ) || ( elecshow ==8 ) || ( elecshow ==9 ) || ( elecshow ==10 ) || ( elecshow ==16 ) )
simply because it's an entirely different operator!
Upvotes: 2