Size of string literal consisting of escaped characters
c++, escaping, sizeof, string, strlen
Solution
This
"\n\r\t"
is a so-called string literal. It is stored in memory as a constant character array with terminating zero. Each escape character is one character.
So this string literal has three explicitly specified characters plus the terminatimg zero. In total there are four characters in the literal.
As for function `strlen` then it does not take into account the terminating zero. So it will report only three characters that were specified explicitly in the string literal.
The function `strlen` uses the terminating zero as the mark where it shall stop to count characters in a string.
As for the operator `sizeof` then it returns total memory in bytes occupied by an object. As your string literal has type `const char[4]` then sizeof will return 4. It is the total memory in bytes occupied by the string literal.
Problem
Code in question: ``` #include <iostream> #include <cstring> using namespace std; int main() { cout << sizeof("\n\r\t") << endl; // prints 4 cout << strlen("\n\r\t") << endl; // print 3 return 0; } ``` I am confused because I always thought that it is standard that `sizeof` char is always 1 byte, but in the above code, it is printing 4. Is there an explanation for this or is there an exception to this rule for escaped characters? Please enlighten me