I know that when we assign a negative value to a unsigned datatype then the two’s compliment of it gets stored, that is the maximum value that the datatype can store minus the negative value we have assigned.
To test that, I have written a program which illustrates that, however I am not able to understand the behavior of char datatype.
#include <iostream>
using namespace std;
template<class T>
void compare(T a,T b)
{
cout<<dec<<"a:"<<(int)a<<"\tb:"<<(int)b<<endl; //first line
cout<<hex<<"a:"<<(int)a<<"\tb:"<<(int)b<<endl; //second line
if(a>b)
cout<<"a is greater than b"<<endl;
else
cout<<"b is greater than a"<<endl;
}
int main()
{
unsigned short as=2;
unsigned short bs=-4;
compare(as,bs);
unsigned int al = 2;
unsigned int bl =-4;
compare(al,bl);
char ac=2;
char bc=-4;
compare(ac,bc);
int ai =2;
int bi =-4;
compare(ai,bi);
}
Output is
a:2 b:65532
a:2 b:fffc
b is greater than a
a:2 b:-4
a:2 b:fffffffc
b is greater than a
a:2 b:-4
a:2 b:fffffffc
a is greater than b
a:2 b:-4
a:2 b:fffffffc
a is greater than b
The compare(…) function is called for times with arguments of different datatypes
- unsigned short- 2 bytes , therefore -4 gets stored as 65532.
- unsigned int – 4 bytes, however as we are trying to typecast it to int while outputting it it is shown -4 in the output, so it is tricking the compiler, however the hex output and the logical comparison result shows that the internal representation is in two’s compliment.
- char – 1 byte, this is where I am getting confused.
- int – 4 bytes, signed datatype, nothing unexpected, normal result.
The question I have to ask is why char is behaving like a signed int?
Even though we are typecasting to int before outputting the first line in the result, why is char showing values similar to int, even when char is 1 byte and int 4 byte. unsigned short showed different value, because its memory requirement was 2 byte.
unsigned int and int is showing same result in the first line of the result, because both are 4 bytes, and the compiler gets tricked successfully, and is acceptable.
But why is char also showing the same value, as if its memory layout was the same as that of int?
And the logical comparison also shows that char does not behave as a unsigned datatype, but a signed one. unsigned datatypes are showing b as greater than one. While char is showing a is greater than b , in terms with signed datatype. Why?
Isn’t char 1 byte unsigned datatype?
This is what I learnt when I did a course on C and C++ in by B.Tech degree.
Any explaination would be helpful.
The compiler used is mingw 2.19.1.
Maybe, maybe not. The signedness of
charis implementation-defined.In your current implementation, it is obviously signed.
And in the output from the
comparemethod, you get four bytes shown, because you cast tointfor the output, so thecharvalue-4gets converted to theintvalue-4.