User:Decltype/sandbox

https://en.wikipedia.org/wiki/User:Ark25/RefScript

In computer programming, the as-if rule is the common name of a clause that gives a large degree of freedom to C and C++ programming language implementations (compilers). While the semantics of C and C++ are described in terms of a theoretical "abstract machine", a real implementation need only emulate the observable behaviour of the machine; that is, it should behave as if all the requirements imposed by the respective language standards were fulfilled from the point of view of the observer.

Definition
A fundamental concept of compiler optimization is that any transformation of the source code that does not alter the behavior or output of the resulting program is allowed. In some programming languages, notably C and C++, this is referred to as the as-if rule. The rule applies equally to the behavior of the executable program, and the process of translating the source text to executable code. Therefore, a conforming C or C++ implementation must in some respects emulate the traditional compiler-linker model, even in the case of an interpreted environment. For example, the lexical analysis of the source code is described as taking place in a number of separate phases. However, the phases are conceptual only, and need not be present in the compiler as long as the result is as if they were.

In the C++ language standard, the as-if rule is defined in section 1.9, paragraph 1: "The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below."

This gives compilers leeway to reorder or eliminate expressions that do not produce side effects altering the program's observable behavior, but implies that the resulting code should mimic the semantics of the original, and not break the rules of the language.

The C++ Standard Library defines its components in terms of a simple interface specification. However, an actual library implementation need only ensure the component behaves as if it has the defined structure.