I was recently looking at string literals in c++, and I saw that string literals were just char
arrays. Then, in many use cases (such as when printing the string literal) the array decays to a pointer to the first element of the char array, and the compiler keeps reading characters until it encounters a null terminator (\0
), at which point the compiler knows the string has ended.
This happens in the example below:
#include <iostream>
int main()
{
char str[] = "This is a string.";
std::cout << str;
}
However, this only makes sense when the string literal is stored somewhere in memory, like how in the example above it was stored in the variable str
. When we do something like this:
#include <iostream>
int main()
{
std::cout << "This is another string";
}
How can the string literal be printed without there being any array? Does the c++ compiler still initialize an array for the string literal and still store the string literal in memory, just without it being done manually? Or is the string printed somehow else?