What does return 0xfe + ceil(x) return?
As I understand, C should convert 0xfe to -2, so the return ought to be ceil(x) - 2 - but the functi开发者_如何学Con seems to return neither of those. What should int m(double x){return 0xfe + ceil(x)}
return?
Apologies for this newbie question. I am not a C programmer in general. Just learning about hex and C.
In the C language, 0xfe
is a hexadecimal int
literal. Specifically, it is equal to 254
, so the result is the double-precision value ceil(x) + 254.0
.
If you explicitly convert to int8_t
or another 8-bit signed type, like so:
(int8_t)0xfe
then you may get the value -2, but this is not guaranteed by the standard. This is because 0xfe
has the value 254, which is not representable in a signed 8-bit field, so the last rule in section 6.3.1.3 of the standard applies:
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
If you want the value -2
, write -2
.
0xfe
is not -2
, it is 254
.
If you want -2
, use "-2
" (or "-0x02
" if you really want to use hex).
In C, 0xfe
never means -2. On the other hand, -2 can sometimes mean 0xfe (if converted, implicitly or explicitly, to unsigned char
).
Like the other answers said, if you want -2, you should use -2.
It is correct that 0xfe can sometimes mean -2, but this is entirely dependent on the datatype the value is stored in. If you only write 0xfe it will be interpreted as an int, and mean 254. If you store it in a signed char (a byte, 8 bits with the range of -128 to 127), it should be interpreted as -2. In c/c++ this datatype is called char, I think C# calls it byte, but I am not sure.
精彩评论