0

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?

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
Aldridge1991
  • 1,326
  • 6
  • 24
  • 51

4 Answers4

4

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.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
3

'?' 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;
kfsone
  • 23,617
  • 2
  • 42
  • 74
1

it means if the expression is true than MDO will have the value of 1 else 0

baliman
  • 588
  • 2
  • 8
  • 27
1

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

odedsh
  • 2,594
  • 17
  • 17