What's the Difference between the number as char and the number as int (or any type, which I can make any arithmetic operation using it like double on c++) on memory - Regarding the equivalent number on the ascii code -. Also, how ('5'-'0') can help me to convert a char into int? what's the mechanism of that?
-
All numbers are the same in C++. As far as how `'5'-'0'` works, that's basic math? Like, subtraction? That's the mechanism? – Sam Varshavchik Aug 13 '22 at 11:53
-
The character `'0'` has a non-zero numeric value (i.e. `int('0') != 0`) and the arabic numerals (`'0'`, `'1'`, `'2'`, .... `'9'`) are a contiguous set (i.e. `'1' - '0' == 1`, `'2' - '0' == 2`, ... `'9' - '0' == 9`) in all standardised character sets (and in the C++ standard). This can be exploited by code converting strings to their numeric values (e.g. `"123"` to `123`). – Peter Aug 13 '22 at 12:17
1 Answers
In this declaration
int num = 5;
the integer variable num
contains the value 5
.
In this declaration
char num = '5';
the character variable num
contains the internal representation of the character literal '5'
that is in ASCII is equal to 53
or 0x35
in hex.
In the source and execution basic character sets the characters '0' - '9'
are stored sequentially without gups. So for example '5' - '0'
that is the same in ASCII as 53 - 48
yields the integer value 5
.
From the C++ Standard
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous
Objects of the type char
used in expressions are usually promoted to the type int
that is called integer promotions.
The type char
can behave as the type signed char
or unsigned char
depending on compiler options.

- 301,070
- 26
- 186
- 335