What does this mean?

Dec 27, 2010 at 10:41am
Greetings All

I'm battling to understand the following code segment:

float m,n,gamma;
...
...
float y1 = (n - m & 1 ? -gamma : gamma);


m, n and gamma are assigned values elsewhere in the code. What I can't figure out are the meanings of "?" and ":" in this context. Would anyone be able to explain this to me?

Cheers

Rich
Last edited on Dec 27, 2010 at 10:42am
Dec 27, 2010 at 10:50am
It's the conditional operator.
 
x = c ? y : z;
means
1
2
3
4
if ( c )
    x = y;
else
    x = z;

See http://www.cplusplus.com/doc/tutorial/operators/
Dec 27, 2010 at 11:13am
Cool Bazzy, thanks for the light speed reply and the link.

So to my understanding, this means

1
2
3
4
5
6
7
8
//if (n - m != 0), y1 = gamma    
//but if n - m = 0, y1 = -gamma    
//i.e.

if (n - m & 1)     
     y1 = gamma;
else
     y1 = -gamma;


assuming that True = 1 and False = NOT 1 in this case... would that be correct?
Last edited on Dec 27, 2010 at 11:44am
Dec 27, 2010 at 12:00pm
1
2
3
4
if ( the last bit of (n-m) is 1 ) // ie:  n-m  is odd
    y1 = -gamma;
else
    y1 = gamma;
Dec 27, 2010 at 12:07pm
Brilliant. That makes sense. Cheers!
Topic archived. No new replies allowed.