我试图在OSX10.5.6上强制使用64位长整数运行在苹果MacBook英特尔酷睿2双核上这是我的c代码:

#include<stdio.h>

int main()
{
    long a = 2147483647; /*== 2^32 - 1*/
    long aplus1;

    printf("a== %d. sizeof(a) == %d  \n", a, sizeof(a));

    aplus1 = a+1;

    printf("aplus1 = %d \n", aplus1);
}

在不使用任何开关的情况下编译会产生以下结果:
$ gcc testlong.c -o testlong ;./testlong

a== 2147483647. sizeof(a) == 4
aplus1 = -2147483648

使用-m64开关编译会得到:
$ gcc testlong.c -o testlong -m64; ./testlong

a== 2147483647. sizeof(a) == 8
aplus1 = -2147483648

所以第二个版本显然是使用64位存储,但是仍然会产生溢出错误,尽管2^32应该在64位整数的范围内有什么想法吗?
我更喜欢一个可以从gcc选项强制执行的解决方案,而不是要求我更改多行源代码(我的实际问题并不是上面的示例,而是需要在更一般的情况下强制执行长整数算法)。

最佳答案

不仅必须使用long long,还必须相应地更改printf()语句。

#include<stdio.h>

int main()
{
    long long a = 2147483647; /*== 2^32 - 1*/
    long long aplus1;

    printf("a== %lld. sizeof(a) == %d  \n", a, sizeof(a));

    aplus1 = a+1;

    printf("aplus1 = %lld \n", aplus1);
}

%lld是long long的代码。
很明显,真正的64位程序可以使用%d作为64位整数-我不知道是否可以将其配置为在此模式下编译。

10-04 22:21
查看更多