チーズ*_*ズパン 4 c unsigned long-integer
我正在完成"以艰难的方式学习C"一书中的练习.练习7要求读者找到unsigned long超出范围的值.
更改
long到unsigned long并设法找到这使得它过大的数量.
所以我的方法是首先获得unsigned long我的机器上的大小:
printf("SIZEOF ULONG: %lu", sizeof(unsigned long));
Run Code Online (Sandbox Code Playgroud)
8结果打印出来.因此,假设unsigned long我的机器上将占用64位,我查找了维基百科上的最大范围.
64位(字,双字,长字,长字,四字,四字,qword,int64)
我期望unsigned long用上面的值声明一个会在没有警告的情况下编译,直到我将值增加1.结果是不同的.编译以下程序会导致警告.
#include <stdio.h>
int main()
{
unsigned long value = 18446744073709551615;
printf("SIZEOF ULONG: %lu", sizeof(unsigned long));
printf("VALUE: %lu", value);
return 0;
}
bla.c: In function ‘main’:
bla.c:5:27: warning: integer constant is so large that it is unsigned
unsigned long value = 18446744073709551615;
^~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
那么为什么gcc抱怨价值大到我想我已经宣布它了unsigned?
int如果十进制整数常量适合该范围,则它们具有类型,否则它们具有类型long或long long.它们没有无符号类型,如果值超出了那些有符号范围,则会收到警告.您需要ul为常量添加后缀以使其具有正确的类型.
在不知道其大小的情况下,还可以更轻松地获得此类型的最大值.只需将-1转换为此类型.
unsigned long value = (unsigned long)-1;
Run Code Online (Sandbox Code Playgroud)
对于不适合 long int(或 long long int,自 C99 和 C++11 起)的值,您需要为整数文字添加后缀。以下任何一项都将符合 unsigned long int:
unsigned long value = 18446744073709551615u;
unsigned long value = 18446744073709551615lu;
unsigned long value = 18446744073709551615ul;
Run Code Online (Sandbox Code Playgroud)
请参阅此处的后缀表:
https://en.cppreference.com/w/c/language/integer_constant(对于 C) https://en.cppreference.com/w/cpp/language/integer_literal(对于 C++)
| 归档时间: |
|
| 查看次数: |
544 次 |
| 最近记录: |