Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...