Is it legal for the C compiler to optimize local static variables?

For a function like

int test(void) {
  static int x = 0;
  x++;
  return 0;
}

- C compiler to optimize x?

For reference, neither GCC 6.3.0 nor Clang 3.9 increase the increment xwith -O3.

+4
source share
1 answer

The compiler will, within the limits of its rights, fully optimize this function, since it has no observable side effects (from the point of view of standard C).

As for why your compilers don't do this, I can't explain it! (Although, of course, they are not required to do this.)

+2
source

Source: https://habr.com/ru/post/1673541/


All Articles