简体   繁体   中英

Do condition expressions always evaluate to 0 or 1 in C?

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 yield 1 if both of its operands compare unequal to 0 ; otherwise, it yields 0 . The result has type int .

C99 §6.5.14/3:

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

C99 6.5.3.3/5:

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0 , 1 if the value of its operand compares equal to 0 . The result has type int . 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM