您好! 我一直在尝试使用 C 语言,直到遇到一些非常奇怪的事情。 我无法自己解释下面显示的结果。
代码:
#include <stdio.h>
int main(void)
{
int num = 4294967295U;
printf("%u\n", num);
return 0;
}
问题:
1.) 如您所见,我创建了一个 int
,它可以保存 -2147483648 到 2147483647 之间的数字。
2.) 当我将值 4294967295 分配给这个变量时,IDE 在编译期间向我显示一条警告消息,因为变量溢出。
3.) 由于好奇,我在数字后面添加了一个U(无符号),当我重新编译它时,编译器没有返回任何警告消息。
4.) 我通过将 U (unsigned) 更改为 L (long) 和 LL (long long) 做了进一步的实验。正如预期的那样,这两个警告消息仍然存在,但在我将其更改为 UL (unsigned Long) 和 ULL (unsigned long long) 之后不再存在。
5.) 为什么会这样?
警告信息:(针对第 2 步)
warning #2073: Overflow in converting constant expression from 'long long int' to 'int'.
警告信息:(针对步骤 4 LL 和 L)
warning #2073: Overflow in converting constant expression from 'long long int' to 'long int'.
最后,感谢您阅读我的问题,非常感谢您的教导和建议。
最佳答案
根据 ISO C99 标准,第 6.4.4.1 节(Integer Constants),Semantics 小节,整数常量的类型是下表中的第一种类型可以表示值的位置:
Octal or Hexadecimal
Suffix Decimal Constant Constant
none int int
long int unsigned int
long long int long int
unsigned long int
long long int
unsigned long long int
u or U unsigned int unsigned int
unsigned long int unsigned long int
unsigned long long int unsigned long long int
l or L long int long int
long long int unsigned long int
long long int
unsigned long long int
both u or U unsigned long int unsigned long int
and l or L unsigned long long int unsigned long long int
ll or LL long long int long long int
unsigned long long int
both u or U unsigned long long int unsigned long long int
and ll or LL
特定实现可以具有遵循与上述相同模式的扩展整数类型。
关于c - 关于C数据类型和常量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5396054/