简体   繁体   中英

What does it mean to subtract '0' from a variable in C?

void push(float[],float);

Here, st[] is float data-type stack and exp[] is char data-type array storing postfix expression.

  push(st,(float)(exp[i]-'0'));

I couldn't figure out the purpose of (exp[i]-'0') section though. Why are we subtracting '0' ?

A character is basically nothing more than an integer, whose value is the encoding of the character.

In the most common encoding scheme, ASCII , the value for eg the character '0' is 48 , and the value for eg '3' is 51 . Now, if we have a variable someChar containing the character '3' and you do someChar - '0' it's the same as doing 51 - 48 which will result in the value 3 .

So if you have a digit read as a character from somewhere, then you subtract '0' to get the integer value of that digit.

This also works on other encodings, not only ASCII, because the C specification says that all encodings must have the digits in consecutive order.

Note that this "trick" is not guaranteed to work for any non-digit character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM