1

I know that if I use a global pointer to a constant string:

const char *h = "hello";

the variable h is stored in the writable data segment. But what if I use

constant pointer to a string

char * const h = "hello";

or a constant pointer to a constant string

const char * const h = "hello";

where would h be stored then?

  • Keep in mind that constant pointers have to be initialized at the declaration, since there is not another chance to assign a value to them. – JFMR Nov 30 '19 at 14:03
  • Given `const char * const h = …`, a C implementation may store `h` in a read-only section or in a writeable section. If the declaration appears inside a function, implementations typically store it on the stack. Due to the nature of the stack, it must be writeable. Given the declaration `const char *h = …`, the compiler may still store `h` in a read-only section if it can determine `h` is never modified. – Eric Postpischil Nov 30 '19 at 14:09
  • 1
    `char * const h = "hello";` no longer compiles in C++ since I think C++11. – HolyBlackCat Nov 30 '19 at 14:15
  • Compiler implementation dependent : https://stackoverflow.com/questions/1576489/where-are-constant-variables-stored-in-c – Build Succeeded Nov 30 '19 at 16:20

2 Answers2

2

The c++ language doesn't specify distinction between different areas of storage, other than these both variables have static storage duration. On one system, they might be stored in same area, on another in separate areas.

Given that the variable is const in the latter case, a language implementation might choose to use an area of memory that is protected from being overwritten.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

First of all, you keep saying pointer to string, which isn't accurate. They're all pointers to a char, and this char is the beginning of the string.

For your question, where h will be stored when it's a constant pointer ?, It will be stored in a readonly part of your RAM. just like any constant variable like const int.

Youssef13
  • 3,836
  • 3
  • 24
  • 41