-1

I have the following program:

#include <stdio.h>
int main ()
{
    
    int x = 8;
    printf("%d %d %d ", x++, x << 2, x >> 1);
 
}

The way I feel like this is supposed to go is this way: The first number should be 8. Then it gets incremented to 9. 9<<2 is 36 so the second %d is 36. The last one is 8 >> 1 which is 4.

However, when I put this into the compiler I get '8 32 4' and not '8 36 4'.

Can someone explain why please?

Thank you!

Elena M.
  • 3
  • 4
  • Function arguments can be evaluated in any order. So the order of side effects is also not guaranteed. – wildplasser Jul 24 '20 at 12:24
  • @P__J__ you are right, it's the wrong dupe. Better would be: https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points although that's labelled C++ rather than C (although in this case, it's the same). – Paul Hankin Jul 24 '20 at 12:35

2 Answers2

2

This operation invokes an Undefined Behavior.

The gcc executes the way you observe, clang does it another way as the result of this program is undefined.

clang also issues a warning

https://godbolt.org/z/GzhPKn

The make program result defined:

int main ()
{    
    int x = 8;
    x++;
    printf("%d %d %d ", x, x << 2, x >> 1);
}
0___________
  • 60,014
  • 4
  • 34
  • 74
0

Argument evaluation order in C and C++ is undefined. Whether the increment or one of the shifts happens first depends on implementation and compiler optimization. It is never advisable to write code like this.

int a() { printf("A"); return 0; }
int b() { printf("B"); return 0; }
int c() { printf("C"); return 0; }

If you do:

printf("%d%d%d", a(), b(), c());

It doesn't necessarily mean you'll get an ABC on your console. Ignore the 0s.

Amal K
  • 4,359
  • 2
  • 22
  • 44