C编译器优化本地静态变量是否合法?

时间:2022-01-02 03:14:06

For a function like

这样的一个函数

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

is a C compiler allowed to optimize out x?

C编译器可以优化x吗?

For reference, neither GCC 6.3.0 or Clang 3.9 optimize out incrementing x with -O3.

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

1 个解决方案

#1


2  

The compiler would be within its rights to optimise away this function completely, given it has no observable side effects (from the point of view of the C standard).

编译器有权完全优化这个函数,因为它没有可见的副作用(从C标准的观点来看)。

As to why your compilers aren't doing so, I can't explain that! (Though of course, they're under no obligation to do so.)

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

#1


2  

The compiler would be within its rights to optimise away this function completely, given it has no observable side effects (from the point of view of the C standard).

编译器有权完全优化这个函数,因为它没有可见的副作用(从C标准的观点来看)。

As to why your compilers aren't doing so, I can't explain that! (Though of course, they're under no obligation to do so.)

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