Andreas
Andreas

Reputation: 7550

Is the result of a boolean operation 1 or 0 in C?

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;

Upvotes: 2

Views: 712

Answers (2)

nj-ath
nj-ath

Reputation: 3146

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

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122383

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.

Upvotes: 8

Related Questions