C中这些数据变量声明差异的原因是什么
what is the reason for these data variables declaration differention in C
unsigned short上限为65535,超过此数从0开始循环;
unsigned short a = 65535;
printf("%d", a);
一=65535
unsigned short a = 65536;
printf("%d", a);
一=0
unsigned short a = 65537;
printf("%d", a);
一=1
等等
但是...声明带计算(pow,multiplication,addition etc.)时,数字没有超过上限。
unsigned short a = pow(2, 16) - 1;
printf("%d", a);
一=65535
unsigned short a = pow(2, 16);
printf("%d", a);
一=65535
unsigned short a = pow(2, 17);
printf("%d", a);
一=65535
...等等
出现这种情况的原因是什么?
- 如果要打印无符号值,请使用正确的格式说明符:
printf("%hu", a);
unsigned short a = pow(2, 16);
值 65536(或更大)不适合 unsigned short
。根据@JohnBollinger 命令,超出范围的浮动值的赋值是 undefined,并且两个不同的编译器甚至相同的编译器取决于优化级别或其他选项可能会产生不同的结果:
https://godbolt.org/z/TG9z8xhaG
gcc - 65535
clang - 0
unsigned short上限为65535,超过此数从0开始循环;
unsigned short a = 65535;
printf("%d", a);
一=65535
unsigned short a = 65536;
printf("%d", a);
一=0
unsigned short a = 65537;
printf("%d", a);
一=1
等等
但是...声明带计算(pow,multiplication,addition etc.)时,数字没有超过上限。
unsigned short a = pow(2, 16) - 1;
printf("%d", a);
一=65535
unsigned short a = pow(2, 16);
printf("%d", a);
一=65535
unsigned short a = pow(2, 17);
printf("%d", a);
一=65535 ...等等
出现这种情况的原因是什么?
- 如果要打印无符号值,请使用正确的格式说明符:
printf("%hu", a);
unsigned short a = pow(2, 16);
值 65536(或更大)不适合unsigned short
。根据@JohnBollinger 命令,超出范围的浮动值的赋值是 undefined,并且两个不同的编译器甚至相同的编译器取决于优化级别或其他选项可能会产生不同的结果:
https://godbolt.org/z/TG9z8xhaG
gcc - 65535
clang - 0