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

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

    Take a look at the ASCII Table, as it probably explains it well enough by itself. The decimal representation for the character '0' is 48, '1' is 49, etc. Most, if not all compilers, follow this conversion table.

    By subtracting '0' (most likely the number 48), you essentially turn the character representation of the variable c into a number representation.

    edit: As mentioned in the comments, I should point out that the number representation of '0' or '9' doesn't necessarily follow the ASCII conversion table (although I believe all common compilers do). This is a technical detail, and belongs in a discussion of the ANSI C specification, and not in an answer directed to someone learning the language.

    Should Ant's happen to write int number = '0';, and wonder why it stores the number 48, it's because his compiler follows the ASCII conversion. This is both useful and helpful for a person learning the basics of C. Show me a compiler that doesn't do this, that isn't some obscure rarity, and I'll gladly leave it at that, but I think more often than not SO values pedantry over helpful replies.

    That said, it's still a good thing to never use the actual number representations. That is, always prefer writing '0' over 48. But it's nice to know why '0' most likely is represented by the number 48.

提交回复
热议问题