The Problem with Implicit Type Conversion
In C and C++ implicit type conversion is often performed by the Compiler when two unequal data types are used in an expression. In most of the cases implicit conversion works fine. But sometimes it might lead to unexpected results and chaos. For example consider the program given below.
int main()
{
int a= -1;
unsigned int b= 1;
if(a<b)
{
printf("\nThis is the expected Output, since a<b!!!\n");
}
else
{
printf("\nThis is the actual Output!!!\n");
}
return 0;
}
Download.
The expected Output is the message "This is the expected Output, since a<b", but the actual Output is the second message "This is the actual Output".
The Figure Below Shows the Output
Why such an Output? The reason is the implicit type conversion by the Compiler. The integer a (By default integer is signed) is converted to an unsigned int and then it is compared with the unsigned integer b. Now the value of b is 1 and the value of a is a very large positive integer (4294967295) since the sign bit is also considered as a magnitude bit. Thus when compared a is larger than b. Hence the else part of the program is executed.