Boltar wrote:
I seem to be having yet more wierd issue with bit shifting. It seems
the following code doesnt do anything under gcc (ie it returns -1 as
both results).
It does something, namely to retain the signedness of your negative
values. It didn't have to. It could have shifted in zeros instead of
replicating the sign bit.
Anyone know why? Is it another language definition or
CPU issue?
It is a mistake on your part. See the code below.
main()
{
printf("%d\n",(int)0xFFFFFFFF >1);
printf("%d\n",(int)-1 >1);
}
#include <stdio.h /* mha: needed for the variadic
function printf */
int /* mha: main returns an int, say so */ main(void)
{
printf("right shifting a negative value has no portably\n"
"defined meaning, so the output of the next two\n"
"printf statements is up for grabs:\n");
printf(" ((int)0xFFFFFFFF >1) = %d\n", (int) 0xFFFFFFFF >1);
printf(" ((int)-1 >) = %d\n\n", (int) -1 >1);
printf("Note the difference in the following:\n");
printf(" (0xFFFFFFFF >1) = %u\n", 0xFFFFFFFF >1);
printf(" (int)(0xFFFFFFFF >1) = %d\n", (int) (0xFFFFFFFF >1));
return 0; /* mha: even if you can get away
without it, it is poor programming
practice not to return a value from
a function returning a value */
}
right shifting a negative value has no portably
defined meaning, so the output of the next two
printf statements is up for grabs:
((int)0xFFFFFFFF >1) = -1
((int)-1 >) = -1
Note the difference in the following:
(0xFFFFFFFF >1) = 2147483647
(int)(0xFFFFFFFF >1) = 2147483647
B2003