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

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

    '0' and '9' are of int types. Their values are 48 and 57 respectively (since 48 and 57 are ASCII values of characters '0' and '9').

    So you are probably holding in n an array for counting digits.

    So this expression (if you are storing digit characters on c):

    ++n[c-'0'];
    

    Means:

    1. Take n's position number c-'0' (c holds a character with a digit on it)
    2. Increment that position by one.

    So n will be:

    n[0] = x; // count of 0 characters
    n[1] = x; // count of 1 characters
    n[2] = x; // count of 2 characters
    n[3] = x; // count of 3 characters
    n[4] = x; // count of 4 characters
    n[5] = x; // count of 5 characters
    n[6] = x; // count of 6 characters
    n[7] = x; // count of 7 characters
    n[8] = x; // count of 8 characters
    n[9] = x; // count of 9 characters
    

    For example, let's say c is equal to character 2. 2's ascii value is 50. So n[50-48] becomes n[2]. So you end up using third element of array n to store 2 character count.

提交回复
热议问题