Why does this compile:
char ch = \'1234\'; //no error
But not anything more than 4 char
s :
char ch = \'12345\'
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'
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 letterL
, as inL’x’
. A character literal that does not begin withL
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 typeint
and implementation-defined value.