Search code examples
c++stringcharacter

How many bytes does a string take? A char?


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.


Solution

  • #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.