18

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Memo
  • 449
  • 3
  • 10

2 Answers2

17

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'
Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
16

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.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • @soandos The digits are treated as normal characters `'1'`, `'2'`, etc. According to the standard, it has implementation-defined value, but normally the value is as @Steve Jessop says in his answer. – Yu Hao Oct 16 '13 at 03:02
  • 1
    The second part of the question: why is it an error at 5 or more characters? Is that implementation defined? – Yakk - Adam Nevraumont Oct 16 '13 at 12:56
  • @Yakk I think so. It's likely that 5 or more characters would hold a value bigger than a 32-bit `int`, and I tested under GCC, it's a warning, not an error. – Yu Hao Oct 16 '13 at 13:05