本文介绍了ANSI C编译器可以去除延迟循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑ANSI C,其唯一目的是推迟执行while循环:

 无符号长计数器= DELAY_COUNT;
而(counter--);

我已经看到了这个用了很多执行上的嵌入式系统,如在哪里延迟。没有睡觉功能和定时器中断或受到限制。

我的ANSI C标准的解读是,这可以通过一个符合标准的编译器可以完全去除。它有没有在描述的副作用 5.1.2.3

...and this section also says:

Does this imply that the loop could be optimised out? Even if counter were volatile?

Notes:

  1. That this is not quite the same as Are compilers allowed to eliminate infinite loops?, because that refers to infinite loops, and questions arise about when a program is allowed to terminate at all. In this case, the program will certainly proceed past this line at some point, optimisation or not.
  2. I know what GCC does (removes the loop for -O1 or higher, unless counter is volatile), but I want to know what the standard dictates.
解决方案

C standard compliance follows the "as-if" rule, by which the compiler can generate any code that behaves "as if" it was running your actual instructions on the abstract machine. Since not performing any operations has the same observable behaviour "as if" you did perform the loop, it's entirely permissible to not generate code for it.

In other words, the time something takes to compute on a real machine is not part of the "observable" behaviour of your program, it is merely a phenomenon of a particular implementation.

The situation is different for volatile variables, since accessing a volatile counts as an "observable" effect.

这篇关于ANSI C编译器可以去除延迟循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 22:59