Please explain what this code is doing (someChar - 48)

前端 未结 4 1229
南旧
南旧 2021-01-05 08:14

I\'m going through some practice problems, and I saw this code:

#include 
#include 

int main(void) {
   char* s = \"357\";
           


        
4条回答
  •  太阳男子
    2021-01-05 09:01

    its adding up 3 + 5 + 7, and then printing

    Sum is 15

    The -48 part is that it is subtracting the character 0, that is, the ascii value for 0.

    So what it does is

    '3' - '0' > 51 - 48
    '5' - '0' > 53 - 48
    '7' - '0' > 55 - 48
    

    As you can see, in C, '0' (character zero) is different from 0 (number 0). They have different values (amongst other things)

提交回复
热议问题