c++ - 在c中访问越界数组

标签 c++ c

<分区>

我看到过一种特殊的代码风格,在我看来这种代码很危险,应该避免,但我在很多地方看到过很多次,所以我很困惑我是否遗漏了什么。

int a[100];

/* Some code later */

for(i =0; (i < 100 && a[i] != 0); i++)
           :
           :

在上面的代码中,表达式 (i < 100 && a[i] != 0) 可能是从右到左求值的,在这种情况下,当 i == 100 时,我们将超出数组'a'。

谁能解释一下这是否是安全代码

最佳答案

  1. 评估或参数的顺序已为&& 明确定义,不能更改。
  2. #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.

注意:强调我的。

关于c++ - 在c中访问越界数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17183019/

相关文章:

android - 为android中的特定api级别编译c++

c - GTK3 设置 GtkButton 大小

c - fork exec 等待命令行输入值的循环

c++ - 再次调用 async_read 会抛出异常

c - 使用C中的函数进行选择排序时出错

objective-c - 我为什么得到:从结果类型为char的函数返回const char *丢弃限定符

c - 帮助我理解这些计算时间

c++ - 在参数 C++ 中传递多个参数而不使用 va_list

c++ - 如何在 Qt 应用程序中通过终端命令运行分离的应用程序?

C++ 多线程 - 子线程何时退出?