-2

Goal

At the end, I want to know why C++ doesn't support char letter = "C"; but does support char letter = 'C'; (notice that the quotation marks are different).

Code

I am using Repl.it as a code platform.

#include <iostream>

int main()
{
    char letter = "C";
    std::cout << letter;
}

Error message

main.cpp: In function 'int main()':

main.cpp:5:19: error: invalid conversion from 'const char*' to 'char' [-fpermissive] char letter = "C";

SAcoder
  • 89
  • 1
  • 3
  • 8
  • 8
    Because that's the syntax. Not much more to it than that... – jhpratt Jan 22 '18 at 23:03
  • 7
    Do you understand why C++ doesn't allow `int i = {1,2,3,4,5};`? It is kind of the same principle. – juanchopanza Jan 22 '18 at 23:03
  • One can always create his own programming language. I guess it works for a master's degree... At least the beginning to it at least. – DeiDei Jan 22 '18 at 23:05
  • "C" is a string. It is zero terminated and is stored in memory. When assigning it gives the address. 'C' is a single byte that is just copied to the variable. – Garr Godfrey Jan 22 '18 at 23:07
  • Because the standard says so: [lex.ccon](http://eel.is/c++draft/lex.ccon#1) – Henri Menke Jan 22 '18 at 23:25
  • Two different things. One is a *string of characters* ("lots of letters"), the other is a *single character* ('A'). So *double quotes* can contain many characters whereas *single quotes* can only contain (logically) one. – Galik Jan 22 '18 at 23:29

2 Answers2

11

They are needed because 'C' and "C" represent completely different types - the first is an integer value, while the second is an array of two characters (the letter 'C' plus an implicit null-terminator). Both are useful, and you need some way of saying which one you want, which is what the different kinds of quotes do.

2

Single quotes are for single characters whereas double quotes are used to create string literals. They mean different things.

See a more thorough explanation.

dwj
  • 3,443
  • 5
  • 35
  • 42
notvita
  • 122
  • 1
  • 8
  • There are things like _multibyte character literals_ in c++. Rarely used, but available. –  Jan 22 '18 at 23:10