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

前端 未结 12 716
旧时难觅i
旧时难觅i 2020-12-09 17:54

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

12条回答
  •  情歌与酒
    2020-12-09 18:24

    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
    

提交回复
热议问题