Condition expression such as those involving && and || , do they always evaluate to 0 or 1? Or for true condition, numbers other than 1 are possible? I am asking because I want to assign a variable like this.
int a = cond1 && cond2;
I was wondering if I should do the following instead.
int a = (cond1 && cond2)? 1:0;
The logical operators ( &&
, ||
, and !
) all evaluate to either 1
or 0
.
C99 §6.5.13/3:
The
&&
operator shall yield1
if both of its operands compare unequal to0
; otherwise, it yields0
. The result has typeint
.
C99 §6.5.14/3:
The
||
operator shall yield1
if either of its operands compare unequal to0
; otherwise, it yields0
. The result has typeint
.
C99 6.5.3.3/5:
The result of the logical negation operator
!
is0
if the value of its operand compares unequal to0
,1
if the value of its operand compares equal to0
. The result has typeint
. The expression !E is equivalent to (0==E).
'&&'
The logical-AND operator produces the value 1 if both operands have nonzero
values. If either operand is equal to 0, the result is 0. If the first operand of a
logical-AND operation is equal to 0, the second operand is not evaluated.
'||'
The logical-OR operator performs an inclusive-OR operation on its operands.
The result is 0 if both operands have 0 values. If either operand has a nonzero
value, the result is 1. If the first operand of a logical-OR operation has a nonzero
value, the second operand is not evaluated.
The operands of logical-AND and logical-OR expressions are evaluated from left to right. If the value of the first operand is sufficient to determine the result of the operation, the second operand is not evaluated. This is called "short-circuit evaluation." There is a sequence point after the first operand.
Thanks, :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.