where are constexpr variables stored

Viewed 143

I saw that constexpr variables are highly discussed on stack overflow. But there is one thing no one talks about:

Where are constexpr variables stored?

Everyone knows the memory location tables of C and C++ programs.

  • stack
  • heap
  • static
  • text

Operating Systems (like Linux)
For operating systems, executable code and all the static variables get copied from the hard drive disc into the allocated areas of text, static ect. in the RAM. From there the program starts as a process.

Embedded Systems (like Atmel Controller)
For an embedded system, this is different. Here the executable code and the literals are permanently stored in a flash Memory; only the static Variables get copied into the RAM.

text or static area
I understand the benefits of constexpr compared to #defines, but for an embedded system programmer, there is always the performance question. On embedded systems, RAM is an expensive resource. So, I need to know if constexpr variables get stored in the text or in the static area. Or more precisely, are they permanently stored in the flash memory or do they get really created as variable into the RAM of an embedded system?

1 Answers

constexpr does not change the storage class of a variable. So the presence of constexpr does not change where the compiler can put the variable.

There are however some important characteristics of constexpr variables. Any variable could have these characteristics, but the constexpr qualifier specifically requires:

  1. The variable cannot be changed (is implicitly const).
  2. The variable is initialized with a compile-time constant expression.

Given these facts, the compiler can put the storage basically anywhere. If the type matches a register type and the value is of sufficient size that it can be loaded via a single "load literal" opcode, the compiler could convert every use of the variable into simply loading the literal value into a register.

Of course, if you start doing things like getting the address of the variable, it may have to take up actual storage. But even that depends on how good the compiler is at inlining.

Related