【发布时间】:2020-06-07 07:02:37
【问题描述】:
这段代码在循环终止条件中有一个错误。 但是,我仍然不明白编译器的决定——它似乎又进入了循环。
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
#define ARR_SIZE 25
int a[ARR_SIZE];
memset (a,1,sizeof(a)); /*filling the array with non-zeros*/
int i = 0;
for (i=0; (a[i] != 0 && i < ARR_SIZE); i++)
{
printf ("i=%d a[i]=%d\n",i,a[i]);
}
return 0;
}
当使用-O2 或-O3 编译它时,循环不会在预期时终止 - 它还会在i == ARR_SIZE 时打印一行。
> gcc -O3 test_loop.c
> ./a.out
i=0 a[i]=16843009
i=1 a[i]=16843009
...
i=23 a[i]=16843009
i=24 a[i]=16843009
i=25 a[i]=32766 <=== Don't understand this one.
> gcc -O0 test_loop.c
> a.out
i=0 a[i]=16843009
i=1 a[i]=16843009
...
i=23 a[i]=16843009
i=24 a[i]=16843009
>
gcc 版本是这样的:gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)
我没有看到 gcc 4.4.7-18 发生这种情况。
ARR_SIZE 的其他尺寸也不会给出相同的结果。
【问题讨论】:
标签: c gcc optimization