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
189 views
in Technique[技术] by (71.8m points)

c++ - What's the real use of using n[c-'0']?

I'm a novice in C and I came across the code like this :

int n[10];
if(c>='0' && c<='9')
++n[c-'0']

In if loop why we have to use single quotes around 0, whats the use of it, why we can't define 0 as an integer straight away? And in the second line of code ++n[c-'0'], whats the use of using array like this, in sense why we need to subtract 0(once again why the use of single quotes in this context?) from c in the array index?

If i do like this n[c-'0'], the result of index operation(c-'0') will be an character or integer?

Given that can anyone say me, whats the real use of such array and what are the disadvantages well?

Thanks in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In C, '0' is an integer whose value represents the digit zero as a character, not the value 0, which would be the null character. Other answers have omitted this, but it's important to note that the C language mandates that the decimal digits have consecutive values, so that if c is a digit, c-'0' is the numeric value of that digit, i.e.

'0'-'0' = 0
'1'-'0' = 1
'2'-'0' = 2
.
.
.
'9'-'0' = 9

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

1.4m articles

1.4m replys

5 comments

57.0k users

...