我看到过一种特殊的代码风格,在我看来这种代码很危险,应该避免,但我在很多地方看到过很多次,所以我很困惑我是否遗漏了什么。
int a[100];
/* Some code later */
for(i =0; (i < 100 && a[i] != 0); i++)
:
:
在上面的代码中,表达式 (i < 100 && a[i] != 0) 可能是从右到左求值的,在这种情况下,当 i == 100 时,我们将超出数组'a'。
谁能解释一下这是否是安全代码
- 评估或参数的顺序已为
&&
明确定义,不能更改。
#1
加上 short circuiting 使其绝对安全。
引用资料:
C++03 标准:
第 5 节:表达式,第 4 段:
except where noted [e.g. special rules for && and ||], the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is Unspecified.
C99 标准:
第 6.5 节:
The grouping of operators and operands is indicated by the syntax.72) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
注意:强调我的。