In C (99), LLONG_MAX
, the maximum value of long long int
type is guaranteed to be at least 9223372036854775807
. The maximum value of an unsigned long long int
is guaranteed to be at least 18446744073709551615
, which is 264−1 (0xffffffffffffffff
).
所以,初始化应该是:
unsigned long long int largestIntegerInC = 18446744073709551615ULL;
(注意ULL
。) 自从largestIntegerInC
属于类型unsigned long long int
,您应该使用正确的格式说明符来打印它,即"%llu"
:
$ cat test.c
#include <stdio.h>
int main(void)
{
unsigned long long int largestIntegerInC = 18446744073709551615ULL;
/* good */
printf("%llu\n", largestIntegerInC);
/* bad */
printf("%d\n", largestIntegerInC);
return 0;
}
$ gcc -std=c99 -pedantic test.c
test.c: In function ‘main’:
test.c:9: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long long unsigned int’
第二printf()
上面是错误的,它可以打印任何东西。您正在使用"%d"
, 意思是printf()
正在期待一个int
,但得到一个unsigned long long int
,(很可能)与int
。你得到的原因-1
因为你的输出是由于(坏)运气,并且事实上在你的机器上,数字是使用二进制补码表示形式来表示的。
为了看看这有多糟糕,让我们运行以下程序:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(int argc, char *argv[])
{
const char *fmt;
unsigned long long int x = ULLONG_MAX;
unsigned long long int y = 42;
int i = -1;
if (argc != 2) {
fprintf(stderr, "Need format string\n");
return EXIT_FAILURE;
}
fmt = argv[1];
printf(fmt, x, y, i);
putchar('\n');
return 0;
}
在我的 Macbook 上,运行该程序"%d %d %d"
给我-1 -1 42
,在 Linux 机器上,具有相同格式的相同程序给了我-1 42 -1
. Oops.
事实上,如果你想存储最大的unsigned long long int
你的号码largestIntegerInC
变量,你应该包括limits.h
并使用ULLONG_MAX
。或者你应该存储 ass-1
到你的变量:
#include <limits.h>
#include <stdio.h>
int main(void)
{
unsigned long long int largestIntegerInC = ULLONG_MAX;
unsigned long long int next = -1;
if (next == largestIntegerInC) puts("OK");
return 0;
}
在上面的程序中,两个largestIntegerInC
and next
包含最大可能的值unsigned long long int
type.