18
votes

Why does this compile:

char ch = '1234'; //no error

But not anything more than 4 chars :

char ch = '12345'; //error: Too many chars in constant

(Yes I know ' ' is used for one char and " " is for strings; I was just experimenting)

Does this have anything to do with the fact that chars are represented using ASCII numbers?

2
What made you think that it shouldn't?AnT
@AndreyT I didn't know about multi-character literals and thought the compiler will reject more than one char in single quotation.Memo
There's no reason at all to use multi-character literals in C++11 because you can just write your own UDL.Simple

2 Answers

17
votes

C++ has something called "multicharacter literals". '1234' is an example of one. They have type int, and it is implementation-defined what value they have and how many characters they can contain.

It's nothing directly to do with the fact that characters are represented as integers, but chances are good that in your implementation the value of '1234' is defined to be either:

'1' + 256 * '2' + 256 * 256 * '3' + 256 * 256 * 256 * '4'

or:

'4' + 256 * '3' + 256 * 256 * '2' + 256 * 256 * 256 * '1'
16
votes

It's a multicharacter literal, and has a type of int.

C++11 §2.13.2 Character literals

A character literal is one or more characters enclosed in single quotes, as in ’x’, optionally preceded by the letter L, as in L’x’. A character literal that does not begin with L is an ordinary character literal, also referred to as a narrow-character literal. An ordinary character literal that contains a single c-char has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set. An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal has type int and implementation-defined value.