【发布时间】:2013-07-22 10:40:04
【问题描述】:
考虑以下代码:
$ cat o.c
#include <stdio.h>
#include <limits.h>
int absolute(int i) {
int j = i < 0 ? -i : i;
if (j<0) /* This is line 6 */
return 0;
return j;
}
int main() {
int i = 1;
printf("%d %d\n", i, absolute(i));
return 0;
}
使用-O2 和-Wstrict-overflow 编译会产生警告:
$ gcc -O2 -Wall -Wextra -Wstrict-overflow o.c
o.c: In function ‘absolute’:
o.c:6:6: warning: assuming signed overflow does not occur when simplifying comparison of absolute value and zero [-Wstrict-overflow]
现在考虑以下在功能上与上述代码等效的代码:
$ cat p.c
#include <stdio.h>
#include <limits.h>
int main() {
int i = 1;
int j = i < 0 ? -i : i;
if (j<0) // Changing i to INT_MIN above and changing (j<0) to (j>INT_MAX)
// doesn't change the behavior
j=0;
printf("%d %d\n", i, j);
return 0;
}
使用相同的选项编译它不会导致任何警告。
$ gcc -O2 -Wall -Wextra -Wstrict-overflow p.c
$
如第二个代码中所述,将赋值更改为 i=INT_MIN; 并将条件更改为 (j>INT_MAX) 也不会发出警告。
我在 Ubuntu 上使用 gcc 4.7.2:
$ gcc --version
gcc (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2
我无法弄清楚这两种情况的区别。它与优化有关还是 gcc 在这里表现不佳?
【问题讨论】:
-
我怀疑在第二种情况下,
j的值在j<0得到优化时是已知的,但我不完全确定。
标签: c gcc compiler-warnings integer-overflow