Bomas
Bomas

Reputation: 43

Pointer to a literal?

While reading C++ Primer, I came across this line:
const char *cp = "Hello World";

To my understanding, "Hello World" is a string literal, which is an array of constant characters. Since an array decays to a pointer to the first element in an array. Does that mean cp points to H which is a literal? Isn't it impossible to have a pointer to a literal, since a pointer has to point to the address of an object in memory?

Upvotes: 4

Views: 727

Answers (1)

Richard Critten
Richard Critten

Reputation: 2145

The storage type of the literals types: boolean, integer, floating, character and nullptr is not specified and therefore they do not need to have a storage location in memory.

The storage type of literal string type is specified: "...String literals have static storage duration, and thus exist in memory for the life of the program..." source: https://en.cppreference.com/w/cpp/language/string_literal

Therefore the address of a literal string can be taken and stored in a const char *.

As suggested by @MichaelKenzel :

From the C++17 draft standard (n4659) https://timsong-cpp.github.io/cppwp/n4659/lex.string#16

Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified. [ Note: The effect of attempting to modify a string literal is undefined.  — end note ]

Upvotes: 4

Related Questions