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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...