Search code examples
c++c++11gccconstantscompiler-optimization

Why gcc does not create a new variable?


I have such code:

static const char kFmt[] = "some string: - %s";
char buf[sizeof(kFmt) + 10];
snprintf(buf, sizeof(buf), kFmt, "string");

It looks like arm gcc 6.3.0 does not create an additional char array kFmt in RAM, but instead just passes the pointer to string literal (stored in flash memory in my case) to snprintf.

But if I remove const and have static char kFmt[] I can see that an additional array is created in RAM and then passed to snprintf.

It is not a problem but I wonder if this behavior is described somewhere in C++ standard or it is compiler optimization and it might differ in different compilers?


Solution

  • The standard does not deal with RAM or flash memory. It is the implementation that decides where and how data are stored.

    However, the standard does say that a const object cannot be modified, so I'd expect a sensible implementation to store static const objects in read-only memory if that's most efficient. On the other hand, non-const objects generally have to live in writable memory.

    [dcl.type.cv]/4:

    Any attempt to modify a const object during its lifetime results in undefined behavior.