C Problem?

unsigned char x=1;
x=(x++)<<3;

Using uVision 6.12
Gives answer of 8
It shifts binary 1 left and doesn't increment.
(even when optimization set to level 0)

Using Micorsoft C++ 6.0
Gives answer of 9
It shifts binary 1 left then increments.


I was a little confused with both answers because I was thought that
the increment would happen first because of the ( ) around x++ then
shift left three giving 16 but that's not the case.

This gives me 16 in both Keil and MS.
x=(++x)<<3; works it gives 16


Parents
  • See "The C Programming Language", second edition, section 2.12. K&R have quite a lot to say about this sort of problem including:

    "One unhappy situation is typified by the statement

    a[i] = i++;
    
    The question is whether the subscript is the old value of i or the new. Compilers can interpret this in different ways and generate different answers depending up their interpretation...."

Reply
  • See "The C Programming Language", second edition, section 2.12. K&R have quite a lot to say about this sort of problem including:

    "One unhappy situation is typified by the statement

    a[i] = i++;
    
    The question is whether the subscript is the old value of i or the new. Compilers can interpret this in different ways and generate different answers depending up their interpretation...."

Children
More questions in this forum