Gian-Carlo Pascutto wrote:
Note that if enum is (a signed) int, and the Scores can be negative (which I think they can for you), then the result of that >> 16 is entirely implementation defined.
Sorry, I don't understand this. Why should be an error a right shift of a negative number ? I would think the right shift of an int is sign extended.
Care to explain ? Thanks.
BTW according to your reasoning, if I have understood correctly, should be wrong also this one:
mcostalba wrote:
Sorry, I don't understand this. Why should be an error a right shift of a negative number ?
It's not an error, it's implementation defined. Meaning, if you switch compilers or compiler versions, or even optimization settings, the result is allowed to change.
If you care for the exact outcome (which I would presume), then the code is wrong.
I would think the right shift of an int is sign extended.
There is nothing in the C standard that guarantees that. See section 6.5.7, point 5:
mcostalba wrote:
Sorry, I don't understand this. Why should be an error a right shift of a negative number ?
It's not an error, it's implementation defined. Meaning, if you switch compilers or compiler versions, or even optimization settings, the result is allowed to change.
If you care for the exact outcome (which I would presume), then the code is wrong.
I would think the right shift of an int is sign extended.
There is nothing in the C standard that guarantees that. See section 6.5.7, point 5:
Gian-Carlo Pascutto wrote:
Note that if enum is (a signed) int, and the Scores can be negative (which I think they can for you), then the result of that >> 16 is entirely implementation defined.
Sorry, I don't understand this. Why should be an error a right shift of a negative number ? I would think the right shift of an int is sign extended.
Care to explain ? Thanks.
BTW according to your reasoning, if I have understood correctly, should be wrong also this one:
From C++ standard which essentially contains the same text as the C standard pointed to by Gian-Carlo regarding shift operators:
5.8 Shift operators
[...]
3 The value of E1 >>E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 divided by the quantity 2 raised to the power E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
I have verified it works with all the compilers and does not rely on shifts or cast to shorts. I have found it googling around and it seems safe to me.
No, for the last one it would have to use something more than 32 bit. In 32 bits, (1<<31) and -(1<<31) are the same number. And in the first example, it would have to use unsigned ints, bit 31 is the sign bit so (1<<31) is negative in signed arithmetic. Your examples would work if you change the 31s to 30s, though.