According to the C++23 standard, what is the output of this program?
#include <iostream>
int main() {
std::cout << sizeof("");
}How does C/C++ know where a C-style string ends? Think about what for instance strlen() does, and what an empty string literal needs to look like for that to work.
1
"" is not completely empty, it has a terminating NULL character:
String literal objects are initialized with the sequence of code unit values corresponding to the string-literal's sequence of s-chars (originally from non-raw string literals) and r-chars (originally from raw string literals), plus a terminating U+0000 NULL character, (...)
Now what's the type of ""? §[lex.string]¶1:
The kind of a string-literal, its type, and its associated character encoding (§[lex.charset]) are determined by its encoding prefix and sequence of s-chars or r-chars as defined by Table 12 where n is the number of encoded code units as described below.
Since "" doesn't have any encoding prefix, according to the Table 12 (§[tab:lex.string.literal]), its type is “array of n const char”. The only code unit we have is a terminating NULL character, so the size of the array is just 1.
Finally, what does sizeof return when applied to an array?
When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.
Our array is 1 element long, so it returns 1 times the size of the element. How big is the element?
The result of
sizeofapplied to any of the narrow character types is1.
Type
charis a distinct type that has an implementation-defined choice of “signed char” or “unsigned char” as its underlying type. The three typeschar,signed char, andunsigned charare collectively called ordinary character types. The ordinary character types andchar8_tare collectively called narrow character types.
So we have one element with size 1, and the program prints 1.