【问题标题】:Do condition expressions always evaluate to 0 or 1 in C?条件表达式在 C 中是否总是计算为 0 或 1?
【发布时间】:2012-07-21 23:57:45
【问题描述】:

&&|| 等条件表达式,总是计算为 0 还是 1?或者对于真实情况,1以外的数字是可能的?我问是因为我想分配这样的变量。

int a = cond1 && cond2;

我想知道是否应该改为执行以下操作。

int a = (cond1 && cond2)? 1:0;

【问题讨论】:

  • 其实,你的主要要求是什么?为什么要分配这些变量?

标签: c semantics logical-operators


【解决方案1】:

逻辑运算符(&&||!)都计算为 10

C99 §6.5.13/3:

如果&& 运算符的两个操作数比较不等于0,则该运算符将产生1;否则,它会产生0。结果类型为int

C99 §6.5.14/3:

如果|| 运算符的任何一个操作数与0 比较不相等,则该运算符将产生1;否则,它会产生0。结果的类型为int

C99 6.5.3.3/5:

如果其操作数的值比较不等于0,逻辑否定运算符! 的结果是0,如果其操作数的值比较等于0,则为1。结果的类型为int。 表达式 !E 等价于 (0==E)。

【讨论】:

  • (我手边没有C11的副本,但我确信逻辑运算符的规范没有改变。)
【解决方案2】:
'&&'
  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. 

逻辑与和逻辑或表达式的操作数从左到右计算。如果第一个操作数的值足以确定运算结果,则不计算第二个操作数。这称为“短路评估”。第一个操作数后面有一个序列点。

谢谢,:)

【讨论】:

  • 这并不能回答问题。
猜你喜欢
  • 2023-01-12
  • 2022-11-03
  • 2011-04-01
  • 2021-08-29
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
相关资源
最近更新 更多