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

前端 未结 12 707
旧时难觅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:49

    It's a way to convert the ascii value of something to its number. In C the ascii value of the char '0' is 48. So subtracting:

    '0' - '0' = 0
    '1' - '0' = 1
     ...
     c - '0' = 
    

    Conveniently the ASCII decimal number increments are consecutive otherwise this trick won't work. In other words c has to be one of '0'..'9' for this to work. This explains the restriction:

    if(c>='0' && c<='9')  
    

提交回复
热议问题