How many bytes does a string take? A char?
The following will take x consecutive chars in memory:
'n' - 1 char (type char)
"n" - 2 chars (above plus zero character) (type const char[2])
'\n' - 1 char
"\n" - 2 chars
"\\n" - 3 chars ('\', 'n', and zero)
"" - 1 char
edit: formatting fixed
edit2: I've written something very stupid, thanks Mooing Duck for pointing that out.
#include <iostream>
int main()
{
std::cout << sizeof 'n' << std::endl; // 1
std::cout << sizeof "n" << std::endl; // 2
std::cout << sizeof '\n' << std::endl; // 1
std::cout << sizeof "\n" << std::endl; // 2
std::cout << sizeof "\\n" << std::endl; // 3
std::cout << sizeof "" << std::endl; // 1
}
- Single quotes indicate characters.
- Double quotes indicate C-style strings with an invisible
NUL
terminator.
\n
(line break) is only a single char and so is \\
(backslash). \\n
is just a backslash followed by n
.
- A
char
, by definition, takes up one byte. - Literals using
'
are char literals; literals using"
are string literals. - A string literal is implicitly null-terminated, so it will take up one more byte than the observable number of characters in the literal.
\
is the escape character and\n
is a newline character.
Put these together and you should be able to figure it out.
'n'
: is not a string, is a literal char, one byte, the character code for the letter n."n"
: string, two bytes, one for n and one for the null character every string has at the end."\n"
: two bytes as \n stand for "new line" which takes one byte, plus one byte for the null char.'\n'
: same as the first, literal char, not a string, one byte."\\n"
: three bytes.. one for \, one for newline and one for the null character""
: one byte, just the null character.