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

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

    Taken out of context, it's impossible to say why the author might have done this.

    What the code does is loop over the characters '0' to '9', possibly to compare them with some user input. During the body of the loop, the characters are mapped to the integers 0..9 for the purposes of indexing the array n.

    Characters in C can behave like integers when involved in arithmetic, by being converted to their ASCII integer representation. The first time through the loop, c is 0, and '0' - '0' is integer 0, regardless of what the integer value of '0' is. That is, x - x will always equal 0; the actual value of x is unimportant in this case.

    Given this, and the fact that the ASCII values are sequential, incrementing from 0 to 9, you can tell that the second time through the loop when c will be '1', that '1' - '0' is integer 1, and so forth.

提交回复
热议问题