C gives different output based on optimization level (new example)

Viewed 108

Based on this very good blog post, The Strict Aliasing Situation is Pretty Bad, I've placed the piece of code online for you to test it:

http://cpp.sh/9kht (output changes between -O0 and -O2)

#include <stdio.h>

long foo(int *x, long *y) {
  *x = 0;
  *y = 1;
  return *x;
}

int main(void) {
  long l;
  printf("%ld\n", foo((int *)&l, &l));
}
  • Is there some sort of undefined behaviour here?

  • What is going on internally when we choose the -O2 level?

2 Answers
Related