是什么在铸造整型常量的编译器? [英] What does the compiler at casting integer constants?
问题描述
使用下面的宏:
#define MIN_SWORD (signed int) 0x8000
在如下面前pression:
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)
一个有些编译器似乎很好地工作。但在其他一些编译器的p21蛋白表达被评价为:
One some compilers it seems to work fine. But on some other compiler the exprssion is evaluated as:
if (s32 < 32768)
我的问题:一个ANSI-C编译器应该如何评估以下EX pression:(长签字)(签字INT)为0x8000
?
看来,在一些编译器中投为`(符号的int)不会导致从正不断的0x8000(预期)转换为符号整数的最小负值,如果事后前pression浇铸到签订了更广泛的类型。
换句话说,所评估的恒定不等同于:
-32768L(但32768L)
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)
这是行为可能是由ANSI-C未定义?
Is this behavior maybe undefined by ANSI-C?
推荐答案
如果一个 INT
是平台上的16位,那么类型为0x8000
是 unsigned int类型
(参见6.4.4第5页的标准)。转换为符号int
是实现定义如果该值不能被重新psented $ P $(见6.3.1.3第3页)。所以,你的code的行为是实现定义的。
If an int
is 16-bit on your platform, then the type of 0x8000
is unsigned int
(see 6.4.4 p.5 of the standard). Converting to a signed 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?
这篇关于是什么在铸造整型常量的编译器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!