printf 中的 Short int 存储超出范围的值
Short int in printf stores a value out of range
为什么可以将 -32 768 存储为 short int?
printf("%hd", -32768);
//returns -32768, no compiler errors
printf("%hd", (short int)-32768);
//returns -32768, no compiler errors
short int a = -32768;
printf("%hd", a);
//returns -32768, no compiler errors
printf("%d", -2147483648);
//compiler returned error as it should
为什么 short int 溢出不会在编译器中引发错误?
printf("%hd", -32769);
//returns 32767, no compiler errors
而
printf("%d", -2147483648);
//compiler returned error
我使用 64 位 ubuntu 16.04 和 gcc 编译器版本 5.4.0。
它与 printf 函数有关?或者我不明白。
将这些值传递给 printf
并没有什么神奇之处。记住,它的原型是int printf(const char*, ...)
。当小于 int
的数字参数通过省略号(参数列表末尾的 ...
)传递时,它会被提升为 int
。因此 printf
期望类型小于 int
的 所有 值作为 int
.
传递
但是,在这种情况下,不涉及积分促销。 -32768
的类型是 int
。 -32769
也一样。由 printf
中的代码来应用格式说明符(此处为 "%hd"
)并尝试理解传递给它的值。此代码传递整数值并声明其类型为 short
。看起来好像可行,但总的来说,不要指望它有任何意义。
关于 (short)-32768
,如果该值适合短(它可能适合;检查 SHORT_MIN
找出答案),没问题。如果不是,转换的结果是实现定义的;这不违法。
最后,-32769
的类型为 int
;没有溢出,你看到的结果只是格式化代码试图从位模式中理解,假设它看到的值是将 short
提升到 [=12 的结果=].同样,不要指望从中得到意义。
为什么可以将 -32 768 存储为 short int?
printf("%hd", -32768);
//returns -32768, no compiler errors
printf("%hd", (short int)-32768);
//returns -32768, no compiler errors
short int a = -32768;
printf("%hd", a);
//returns -32768, no compiler errors
printf("%d", -2147483648);
//compiler returned error as it should
为什么 short int 溢出不会在编译器中引发错误?
printf("%hd", -32769);
//returns 32767, no compiler errors
而
printf("%d", -2147483648);
//compiler returned error
我使用 64 位 ubuntu 16.04 和 gcc 编译器版本 5.4.0。 它与 printf 函数有关?或者我不明白。
将这些值传递给 printf
并没有什么神奇之处。记住,它的原型是int printf(const char*, ...)
。当小于 int
的数字参数通过省略号(参数列表末尾的 ...
)传递时,它会被提升为 int
。因此 printf
期望类型小于 int
的 所有 值作为 int
.
但是,在这种情况下,不涉及积分促销。 -32768
的类型是 int
。 -32769
也一样。由 printf
中的代码来应用格式说明符(此处为 "%hd"
)并尝试理解传递给它的值。此代码传递整数值并声明其类型为 short
。看起来好像可行,但总的来说,不要指望它有任何意义。
关于 (short)-32768
,如果该值适合短(它可能适合;检查 SHORT_MIN
找出答案),没问题。如果不是,转换的结果是实现定义的;这不违法。
最后,-32769
的类型为 int
;没有溢出,你看到的结果只是格式化代码试图从位模式中理解,假设它看到的值是将 short
提升到 [=12 的结果=].同样,不要指望从中得到意义。