greets,
I was reading a tutorial on #define and const and there is an example there:
#define AbsoluteValue(x) (x >= 0 ? x : -x)
I don't understand how (x >= 0 ? x : -x) works.
can some explain it?
thanks!
greets,
I was reading a tutorial on #define and const and there is an example there:
#define AbsoluteValue(x) (x >= 0 ? x : -x)
I don't understand how (x >= 0 ? x : -x) works.
can some explain it?
thanks!
It's a compact IF/ELSE statement.
if( x >= 0)
{
//if true
return x;
}
else
{
// otherwise false
return -x; // x *= -1
}
It's a shorthand way of saying
if(x>=0)
x=x;
else
x=x*-1;
You can use this in many places the common form is (condition)? valueIfTrue:valueIfFalse;
some more examples
Serial.print((id==7)? "hello Brian":"who are you?");
x=(scale=='F')? temperature * 5/9 : temperature;
There are many uses for it,
If the true or false parts are an lvalue expression, so is the result:
( val ? PORTA : PORTB ) &= ~_BV( 2 );
For more reading, I wrote an article on the conditional operator.