什么时候可以完全优化易失性变量?

考虑以下代码示例:
int main(void)
{
  volatile int a;
  static volatile int b;

  volatile int c;
  c = 20;
  static volatile int d;
  d = 30;

  volatile int e = 40;
  static volatile int f = 50;

  return 0;
}

如果没有volatile,编译器可以优化掉所有变量,因为它们永远不会被读取.

我认为a和b可以被优化掉,因为它们完全没用,见unused volatile variable.

我认为c和d无法被删除,因为它们被写入,并且写入volatile变量必须实际发生. e应该相当于c.

GCC不会优化f,但它也不会发出任何写入指令.在数据部分中设置50. LLVM(clang)完全删除f.

这些陈述是真的吗?

>如果永远不会访问volatile变量,则可以将其优化掉.
>静态或全局变量的初始化不计为访问.

解决方法

写入volatile变量(甚至是自动变量)计为可观察行为.

C11(N1570)5.1.2.3/6:

The least requirements on a conforming implementation are:

— Accesses to volatile objects are evaluated strictly according to the rules of the abstract
machine.

— At program termination,all data written into files shall be identical to the result that
execution of the program according to the abstract semantics would have produced.

— The input and output dynamics of interactive devices shall take place as specified in
7.21.3. The intent of these requirements is that unbuffered or line-buffered output
appear as soon as possible,to ensure that prompting messages actually appear prior to
a program waiting for input.

This is the observable behavior of the program.

问题是:初始化(e,f)算作“访问”吗?正如Sander de Dycker所指出的那样,6.7.3说:

What constitutes an access to an object that has volatile-qualified type is implementation-defined.

这意味着由编译器决定是否可以优化e和f – 但必须记录下来!

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...