2

Is the result of a boolean operation guaranteed to be 1 or 0?

I'm programming a microcontroller and need to set a pin to 1 or 0, and was wondering if I can shorten the code from this:

isRunning = isStarted && !isSleeping;
_PBH0 = isRunning ? 1 : 0;

to this:

isRunning = isStarted && !isSleeping;
_PBH0 = isRunning;
Andreas
  • 7,470
  • 10
  • 51
  • 73

2 Answers2

7

Yes, the result of && operator (or any of the logical operators) is an int that has a value of either 1 or 0.

C11 §6.5.13 Logical AND operator

The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
2

Infact, you can reduce to_PHB0 = (isStarted && !isSleeping);

nj-ath
  • 3,028
  • 2
  • 25
  • 41