I am having problem comparing an int value and a char value in C. Lets say I variable int value1 that is 0 and a char that has value '0'. I know that that char's value is actually an ascii number and that '0' is 48, but how do I compare int's 0 value with chars '0' value, in an if statement as a example?
Asked
Active
Viewed 80 times
0
-
"is actually an ascii number" - not necessarily. – Bathsheba Sep 27 '17 at 11:53
-
`if(int_value == char_value - '0')` – BLUEPIXY Sep 27 '17 at 11:55
-
You should also cast the result (int)(char_value - '0') or the compiler will issue warnings. – SPlatten Sep 27 '17 at 11:58
1 Answers
2
You can use the idiom c - '0'
to convert a char
c
to its equivalent digit.
This is an expression of type int
.
Note that it works in any character encoding supported by the C Standard, since such an encoding must order 0 to 9 consecutively.

Bathsheba
- 231,907
- 34
- 361
- 483