C++ – How Does Const Storage Work? (Item 2, Scott Meyers Effective C++)

ccomputer science

In Item2 on page 16, (Prefer consts, enums, and inlines to #defines), Scott says:

Also, though good compilers won't set aside storage for const objects of integer types…

I don't understand this. If I define a const object, eg

const int myval = 5;

then surely the compiler must set aside some memory (of int size) to store the value 5?

Or is const data stored in some special way?

This is more a question of computer storage I suppose. Basically, how does the computer store const objects so that no storage is set aside?

Best Answer

Also, though good compilers won't set aside storage for const objects of integer types...

A slightly more correct statement would be that compilers wouldn't set aside data memory for const objects of integer type: they would trade it for program memory. There is no difference between the two under Von Neumann architecture, but in other architectures, such as Harvard, the distinction is rather important.

To fully understand what's going on, you need to recall how assembly language loads data for processing. There are two fundamental ways to load the data - read a memory from a specific location (so called direct addressing mode), or set a constant specified as part of the instruction itself (so called immediate addressing mode). When compiler sees a const int x = 5 declaration followed by int a = x+x, it has two options:

  • Put 5 in a data memory, as if it were a variable, and generate direct load instructions; treat writes to x as errors
  • Each time the x is referenced, generate an immediate load instruction of the value 5

In the first case you will see a read from x into the accumulator register, an addition of the value at the location of x to accumulator, and a store into the location of a. In the second case you will see a load immediate of five, an add immediate of five, followed by a store into the location of a. Some compilers may figure out that you are adding a constant to itself, optimize a = x+x into a = 10, and generate a single instruction that stores ten at the location of a.