Looking for some code to reuse in my C app I came across this expression:
MDO = ((output_data & 0x80) ? 1 : 0);
I understand what is between brackets but what does ? 1 : 0
mean?
Looking for some code to reuse in my C app I came across this expression:
MDO = ((output_data & 0x80) ? 1 : 0);
I understand what is between brackets but what does ? 1 : 0
mean?
It is shorthand for if-else
, called the ternary operator.
In your case it is equal to:
if (output_data & 0x80) {
MDO = 1;
} else {
MDO = 0;
}
And a little word of advice, don't use it for complicated if
constructs, it hinders readability. Only use it in cases like this, where it can be understood immediately.
'?' is the ternary operator, it's a short-hand for
if ((output_data & 0x80) != 0) { MDO = 1; } else { MDO = 0; }
which will assign 1
to MDO if output_data has bit 8 set (0x80 = 128 = bit 8), otherwise MDO gets the value of 0
A simpler example: There are 10 beers on Friday, otherwise there's only 2.
int beers = (day == Friday) ? 10 : 2;
output_data& 0x80 is a bitwise binary and. So it returns 0x80 if that particualr bit is on out_putdata otherwise it returns 0
MDO= ? :
Is the same as
if (expression)
MDO = 1
else
MDO = 0
so MDO will be 1 if the bit is on on output_data otherwise it is 0