Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 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 Reply

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...