I am fairly new to C++ and i have some trouble in understanding character subtraction in c++.
I had this code intially
char x='2';
x-='0';
if(x) cout << "More than Zero" << endl;
This returned More than Zero as output so to know the value of x i tried this code.
char x='2';
x-='0';
if(x) cout << x << endl;
And i am getting null character(or new line) as output.
Any help is appreciated.
You are substracting 48 (ascii char '0') to the character 50 (ascii '2')
According to the C++ Standard (2.3 Character sets)
So the codes of adjacent digits in any character set differ by 1.
Thus in this code snippet
the difference between
'2'
and'0'
(the difference between codes that represent these characters; for example in ASCII these codes are 0x32 and 0x30 while in EBCDIC they are 0xF2 and 0xF0 correspondingly) is equal to2
.You can check this for example the following way
or
If you just write
then the operator << tries to output
x
as a printable character image of the value2
becausex
is of typechar
.So what your code is doing is the following:
x = '2', which represents 50 as a decimal value in the ASCII table.
then your are basically saying:
x = x - '0', where zero in the ASCII table is represented as 48 in decimal, which equates to x = 50 - 48 = 2.
Note that 2 != '2' . If you look up 2(decimal) in the ASCII table that will give you a STX (start of text). This is what your code is doing. So keep in mind that the subtraction is taking place on the decimal value of the char.
In C/C++ characters are stored as 8-bit integers with ASCII encoding. So when you do
x-='0';
you're subtracting the ASCII value of '0' which is 48 from the ASCII value of '2' which is 50. x is then equal to 2 which is a special control character stating STX (start of text), which is not printable.If you want to perform arithmetic on characters it's better to subtract '0' from every character before any operation and adding '0' to the result. To avoid problems like running over the range of the 8bit value I'd suggest to cast them on ints or longs.
It's much safer to perform these operations on larger value types, and subtracting the '0' character allows you to perform operations independent on the ASCII encoding like you'd do with casual integers. Then you add '0' to go back to the ASCII encoding, which alows you to print a number.
In C++, characters are all represented by an ASCII code (see http://www.asciitable.com/) I guess that doing :
is like doing
According to the ASCII table, the ASCII code 2 stands for start of text, which is not displayed by cout.
Hope it helps.