babycub
babycub

Reputation: 31

Are const built in types inlined in c++?

I looked the C++14 reference and could not see where the standard would says that the const built in types are inlined by the compiler and not allocated. i.e. the claim is

const int i = 5;
std::cout<<i;

everywhere i is used with be replaced with 5 and no memory space will be allocated. Can someone please point to the standard section ?

Upvotes: 3

Views: 94

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158619

Sounds like a combination of two concepts odr use and the as-if rule.

Odr-use, which would be covered in covered in section 3.2 One definition rule but we can also find some relevant section in 4.1 Lvalue-to-rvalue conversion which says:

When an lvalue-to-rvalue conversion is applied to an expression e, and either

  • e is not potentially evaluated, or
  • the evaluation of e results in the evaluation of a member ex of the set of potential results of e, and ex names a variable x that is not odr-used by ex (3.2),

the value contained in the referenced object is not accessed.

and has the following involved example which seems to show a captured by reference local variable being used outside of its lifetime but is actually not the case since it is not odr-used and therefore does not actually require the object to be allocated and thus can be optimized away.

[ Example:

struct S { int n; };
auto f() {
    S x { 1 };
    constexpr S y { 2 };
    return [&](bool b) { return (b ? y : x).n; };
}    
auto g = f();
int m = g(false); // undefined behavior due to access of x.n outside its lifetime
int n = g(true); // OK, does not access y.n

—end example ]

This comes down to the as-if rule which says the compiler only has the emulate the observable behavior of a program, basically it governs what optimizations are allowable. Even though an optimization may be allowable the compiler does not have to perform the optimization. If an object yields a constant expression and the address is not required then by the as-if rule no memory needs to be allocated for it since the effect of not allocating memory would not be observable.

Upvotes: 2

Thomas Matthews
Thomas Matthews

Reputation: 57749

In most cases, the compiler will emit processor instructions containing the constant value and not allocate a read/write memory location. But this depends on the compiler settings.

The compiler may elect to place the constants into a read-only section of memory. It may place the constant into the executable.

Print out the assembly language listing of the function to see the truth.

Upvotes: 1

Related Questions