I have been wondering if there is any difference between what is being pointed by ptrToArray
and ptrToLiteral
in the following example:
constexpr char constExprArray[] = "hello";
const char* ptrToArray = constExprArray;
const char* ptrToLiteral = "hello";
constExprArray
and the two "hello"
literals are all compile time constant lvalues correct?In C the type of a string literal is a char[]. In C++, an ordinary string literal has type 'array of n const char'. For example, The type of the string literal "Hello" is "array of 6 const char". It can, however, be converted to a const char* by array-to-pointer conversion.
String literals have static storage duration, and thus exist in memory for the life of the program. String literals can be used to initialize character arrays.
constexpr std::string While it's best to rely on string_views and not create unnecessary string copies, the example above shows that you can even create pass vectors of strings inside a constexpr function!
String literals. A string literal represents a sequence of characters that together form a null-terminated string. The characters must be enclosed between double quotation marks.
A string literal and a constexpr array of char are almost identical. A pointer to either is an address constant expression. An lvalue-to-rvalue conversion is permitted on their elements in a constant expression. They both have static storage duration. The only difference that I know of is that a string literal can initialize an array whereas a constexpr array cannot:
constexpr char a[] = "hello";
constexpr char b[] = a; // ill-formed
constexpr char b[] = "hello"; // ok
To get around this you can wrap the array in a class of literal type. We are currently looking at standardizing such a wrapper that will be called std::string_literal
or similar, but for now you will have to do this by hand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With