C 编译器优化局部静态变量是否合法?

Eri*_*tin 5 c static local compiler-optimization

对于像这样的函数

int test(void) {
  static int x = 0;
  x++;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

C 编译器允许优化吗x

作为参考,GCC 6.3.0 或 Clang 3.9 都没有优化使用x-O3 的增量。

Oli*_*rth 2

编译器有权完全优化该函数,因为它没有明显的副作用(从 C 标准的角度来看)。

至于为什么你的编译器不这样做,我无法解释!(当然,他们没有义务这样做。)