I'm doing a review of my first semester C++ class, and I think I missing something. How many bytes does a string take up? A char?
The examples we were given are, some being character literals and some being strings:
'n', "n", '\n', "\n", "\\n", ""
I'm particularly confused by the usage of newlines in there.
#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.
'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 the null character"": one byte, just the null character.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