How do char and int work in C++ -
may i'm going ask stupid question, want confirm how char works? let me explain examples want ask. let suppose declare char variable , input 6 or integer character.
#include <iostream> using namespace std; int main(){ char a; cin >> a; cout << a*a; // know here input's ascii value multiply return 0; } same 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 question clear.
char fundamental data type, of size 1 byte (not 8bits!!!), capable of representing @ least ascii code range of characters. so, example, char x = 'a'; stores ascii value of 'a', in case 97. however, ostream operators overloaded "know" how deal char, , instead of blindly displaying 97 in line cout << x; display ascii representation of character, i.e. 'a'.
however, whenever a * a, compiler performs what's called integral promotion, , implicitly converts data in char int. so, compiler, expression a * a translated (int)a * (int)a, result of 97 * 97, end displaying 9409.
note compiler char , int 2 different types. can differentiate between two. operator<< displays character when input of type char or of type implicitly convertible char.
Comments
Post a Comment