在Mac OS上,`cc -std=c99`和`c99`有什么区别?

6

考虑下面这个程序:

/*  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 OS系统上(Xcode 3.2.3),如果我使用cc编译并使用-std=c99标志,一切似乎都很正确:

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.

你能解释一下这种行为吗?

1
不能使用1000000作为例子来展示差异并更快地计算吗?;) - kennytm
1
你尝试过使用两个编译器编译代码并逐步执行吗?我想在其中一个编译器中,unsigned long int 是32位的,在另一个编译器中则是64位的。 - Jeff Mercado
2个回答


5
在Mac OS X下,cc是指向gcc的符号链接(默认为64位),而c99不是(默认为32位)。
/usr/bin/cc -> gcc-4.2
它们对于数据类型使用不同的默认字节大小。
/** sizeof.c */ #include #include int main(int argc, char *argv) { printf("sizeof(unsigned long int)==%d\n", (int)sizeof(unsigned long int));
return EXIT_SUCCESS; }
cc -std=c99 sizeof.c ./a.out sizeof(unsigned long int)==8
c99 sizeof.c ./a.out sizeof(unsigned long int)==4
简单来说,当使用c99编译器时,您正在溢出(也称包装)整数变量。
.PMCD.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接