May be I'm going to ask a stupid question, but I want to confirm that how char works? Let me explain with examples what i want to ask.
Let suppose I declare a char variable
and then input 6
or any integer character.
#include <iostream>
using namespace std;
int main(){
char a;
cin >> a;
cout << a*a; // I know here input's ASCII value will multiply
return 0;
}
Same as for integer input 6
#include <iostream>
using namespace std;
int main(){
int a;
cin >> a;
cout << a*a; // Why compiler not take input's ASCII Value here?
return 0;
}
I think now my question is clear.
char
is a fundamental data type, of size 1 byte (not necessarily 8bits!!!), capable of representing at least the ASCII code range of all characters. So, for example,char x = 'a';
really stores the ASCII value of'a'
, in this case 97. However, theostream
operators are overloaded so they "know" how to deal withchar
, and instead of blindly displaying97
in a line likecout << x;
they display the ASCII representation of the character, i.e.'a'
.However, whenever you do
a * a
, the compiler performs what's called integral promotion, and implicitly converts the data in thechar
to anint
. So, for the compiler, the expressiona * a
is translated into(int)a * (int)a
, which is the result of97 * 97
, so you end up displaying9409
.Note that for the compiler
char
andint
are two different types. It can differentiate between the two. Sooperator<<
displays a character only when the input is of typechar
or of a type implicitly convertible tochar
.