给定以下程序:
/* Find the sum of all the multiples of 3 or 5 below 1000. */
#include <stdio.h>
unsigned long int method_one(const unsigned long int n);
int
main(int argc, char *argv[])
{
unsigned long int sum = method_one(1000000000);
if (sum != 0) {
printf("Sum: %lu\n", sum);
} else {
printf("Error: Unsigned Integer Wrapping.\n");
}
return 0;
}
unsigned long int
method_one(const unsigned long int n)
{
unsigned long int i;
unsigned long int sum = 0;
for (i=1; i!=n; ++i) {
if (!(i % 3) || !(i % 5)) {
unsigned long int tmp_sum = sum;
sum += i;
if (sum < tmp_sum)
return 0;
}
}
return sum;
}在Mac系统(Xcode3.2.3)上,如果我使用-std=c99标志使用cc进行编译,一切似乎都恰到好处:
nietzsche:problem_1 robert$ cc -std=c99 problem_1.c -o problem_1
nietzsche:problem_1 robert$ ./problem_1
Sum: 233333333166666668但是,如果我使用c99编译它,将会发生以下情况:
nietzsche:problem_1 robert$ c99 problem_1.c -o problem_1
nietzsche:problem_1 robert$ ./problem_1
Error: Unsigned Integer Wrapping.你能解释一下这种行为吗?
发布于 2010-11-15 16:02:22
c99 is a wrapper of gcc。它之所以存在,是因为POSIX需要它。默认情况下,c99将生成32位(i386)二进制文件。
cc is a symlink to gcc,所以它采用gcc拥有的所有默认配置。默认情况下,gcc在本机架构中生成一个二进制文件,即x86_64。
在OS X上的i386上,unsigned long是32位长,在x86_64上是64位长。因此,c99将有一个cc -std=c99没有的“无符号整数包装”。
您可以通过-W 64标志强制c99在OS X上生成64位二进制文件。
c99 -W 64 proble1.c -o problem_1(注意:我所说的gcc是指像i686-apple-darwin10-gcc-4.2.1这样的实际的gcc二进制文件。)
https://stackoverflow.com/questions/4182413
复制相似问题