1

I didn't think these if's would compile but they do:

if (a>>b&&c&&d)

if (month==1,2,3,5,7,9,10) 

The first I'm clueless about. In the second statement is the comma supposed to be an (||) or operator ? Syntax wise was it always this way or was it introduced some time ago ?

I'm using Visual Studio 2010.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
serj
  • 508
  • 4
  • 20
  • 3
    The first has a bitshift and logical ands, and the comma operator is not the same as logical or, otherwise it wouldn't exist. It's not hard to research the comma operator. – chris Nov 18 '13 at 16:28
  • For the second one see [return list of values between parenthesis (10, 20, 30, 40)?](http://stackoverflow.com/questions/20001349/return-list-of-values-between-parenthesis-10-20-30-40) – Shafik Yaghmour Nov 18 '13 at 16:29
  • 3
    Just because it compiles, does not mean it's doing what you think it's doing. Research the operators you're using before you use them if you're unsure - there's plenty of questions on this already. – The Forest And The Trees Nov 18 '13 at 16:29
  • possible duplicate of [Comma Operator in Conditon of Loop in C](http://stackoverflow.com/questions/12959415/comma-operator-in-conditon-of-loop-in-c) – Raymond Chen Nov 18 '13 at 16:38
  • You are right, I should've searched for the comma operator. – serj Nov 19 '13 at 12:54

2 Answers2

3
if (a>>b && c && d)

it is equal to

if ((a>>b) && c && d)

if the result of a shifted right b times evaluates to a bool, c and d also evaluates to bool respectively, then all these booleans will be AND-ed to each other.

 

In your context, the all expressions within commas will be evaluated and then the last expression will be passed to if expression:

if (month==1,2,3,5,7,9,10) -> is equal to
if (2,3,5,7,9,10)          -> is equal to
if (3,5,7,9,10)            -> is equal to
if (5,7,9,10)              -> is equal to
if (7,9,10)                -> is equal to
if (9,10)                  -> is equal to
if (10)

which is always true.

 

It's not suppose to be || or &&. If you want OR or AND write it like below:

if (month==1 || month==2 || month==3 || ....)

or

if (month==1 && month==2 && month==3 && ....)
// Also month can not simultaneously be equal to more than one value!
// then, it's equal to
if (false) 
masoud
  • 55,379
  • 16
  • 141
  • 208
2

The first if statement would be evaluated like:

if(((a >> b) && c) && d)

Essentially bitshift a by b bits and then logical and with c and then with d

The second is the comma operator which will evaluate the first term and throw it away, then the second, and so on and return the result of the final term. So in our case the statement is equivalent to:

if(10)

which is always true.

pippin1289
  • 4,861
  • 2
  • 22
  • 37