Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code with '1234' compile in C++?

Tags:

c++

char

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?

like image 596
Memo Avatar asked Oct 16 '13 02:10

Memo


Video Answer


2 Answers

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'
like image 174
Steve Jessop Avatar answered Oct 02 '22 08:10

Steve Jessop


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.

like image 40
Yu Hao Avatar answered Oct 02 '22 09:10

Yu Hao