编译器在转换整型常量时做什么?
使用以下宏:
#define MIN_SWORD (signed int) 0x8000
在例如以下表达式中:
signed long s32;
if (s32 < (signed long)MIN_SWORD)...
预计会执行以下检查:
if (s32 < -32768)
一些编译器似乎工作正常。但在其他一些编译器上,表达式的计算结果为:
if (s32 < 32768)
我的问题: ANSI-C 编译器应该如何计算以下表达式: (有符号长整型)(有符号整型)0x8000
?
似乎在某些编译器上,转换为 `(signed int) 不会导致从正常量 0x8000 到有符号 int 的最小负值的(预期)转换,如果随后将表达式转换为更广泛的有符号长类型。 换句话说,计算的常量不等于: -32768L(但 32768L)
此行为可能未由 ANSI-C 定义吗?
Using the following macro:
#define MIN_SWORD (signed int) 0x8000
In e.g. the following expression:
signed long s32;
if (s32 < (signed long)MIN_SWORD)...
is expected to do the following check:
if (s32 < -32768)
One some compilers it seems to work fine. But on some other compiler the exprssion is evaluated as:
if (s32 < 32768)
My question: How is a ANSI-C compiler supposed to evaluate the following expression:(signed long) (signed int) 0x8000
?
It seems that on some compilers the cast to `(signed int) does not cause the (expected) conversion from the positive constant 0x8000 to the minimum negative value of a signed int, if afterwards the expression is casted to the wider type of signed long.
In other words, the evaluated constant is not equivalent to:
-32768L (but 32768L)
Is this behavior maybe undefined by ANSI-C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
int
在您的平台上是 16 位,则0x8000
的类型是unsigned int
(参见 6.4.4 p.5)标准)。如果无法表示该值,则转换为signed int
是实现定义的(请参阅 6.3.1.3 p.3)。因此,代码的行为是实现定义的。话虽如此,在实践中,我会认为这应该始终符合您的“期望”。这是什么编译器?
If an
int
is 16-bit on your platform, then the type of0x8000
isunsigned int
(see 6.4.4 p.5 of the standard). Converting to asigned int
is implementation-defined if the value cannot be represented (see 6.3.1.3 p.3). So the behaviour of your code is implementation-defined.Having said that, in practice, I would've assumed that this should always do what you "expect". What compiler is this?