Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 258
Moshe Avatar asked Feb 21 '12 20:02

Moshe


2 Answers

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

like image 120
fredoverflow Avatar answered Oct 24 '22 07:10

fredoverflow


  • '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.
like image 28
gztomas Avatar answered Oct 24 '22 05:10

gztomas