使用foo()&& amp;是否安全C中0?

时间:2013-11-10 22:44:58

标签: c

想象一下,我有以下一段C代码,其中foo()产生副作用并返回一个整数:

if(bar) {
    foo();
    return 0;
}

现在,说我真的很喜欢让我的代码变得紧凑,可能需要读者付费,我将其更改为:

if (bar)
    return foo() && 0;

我可以确定这两段代码会产生相同的行为吗,或者我是否会因为可能的编译器优化或类似的事情而冒险调用foo(),从而不会产生所需的副作用?

注意:这不是关于哪一段代码更好的问题,而是这两段在所有情况下是否实际产生相同的行为。我认为大多数(和我)都同意应该使用前一段代码。

3 个答案:

答案 0 :(得分:3)

是的,那两个是一样的。始终会调用foo()(假设bar为真)。

答案 1 :(得分:1)

为什么在后者中混淆代码?

使用前者。

易于阅读,即这更容易理解

if(bar) {
    foo();
    return 0;
}

或者除非出现工作保障问题

答案 2 :(得分:1)

您提供的两种表格是等效的。 C11标准(草案n1570)声明,

6.5.13 Logical AND operator
...
Semantics

3 The && operator shall yield 1 if both of its operands compare unequal to 0;
  otherwise, it yields 0. The result has type int.
4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right
  evaluation; if the second operand is evaluated, there is a sequence point between
  the evaluations of the first and second operands. If the first operand compares
  equal to 0, the second operand is not evaluated.

到目前为止,所有C标准中都出现过类似的语言。

你可能更喜欢在这里使用逗号运算符(return foo(), 0;),因为:

  • 它更短(操作员一个字符对两个字符,使用逗号时可以删除左侧空格字符,总共少两个字符)。
  • 它为您提供了更大的灵活性,因为您可以返回非标量类型(例如结构),以及比0或1更宽范围的整数。
  • 它更好地表达了意图:“放弃foo()的返回值并返回其他内容(0)”。

现在,如果你有机会删除对foo()的调用,那么编译器就会设法证明foo()是一个没有明显副作用的函数,或者更可能是一个严重的错误,你应该报告它。

相关问题