C++ Type compatibility
c++ is very strict with the type compatibility as compared to C language. for instance, c++ language defines int, short int, and long int as three different types, although each of these has size of one byte. In C++ language the types of values must be the same for complete compatibility, or a cast must be applied. These restrictions in c++ are necessary in order to support function overloading where two functions with the same name are distinguished using the type of function arguments
another major difference is the way char constants are stored. in C programming, they are stored as ints, and therefore
is equivalent to sizeof(int) in c language, in c++ language, however, char is not promoted to the size of int and therefore sizeof(‘y’) equals sizeof(char)
Type Compatibility
C++ is very strict with regard to type compatibility as compared to C programming. Type compatibility is very
close to implicit or automatic type conversion. The type compatibility is being able to use two types being able to substitute one for the other without modification and together without modification.
The type compatibility is categorized into following three types by the compiler:
1. Assignment compatibility
In assignment compatibility, if the one type of variable assigned to another type variable is different
It will results into loss of value of assigned variable if the size of the assigned variable is large than the size of variable to which it is assigned.
For example
float f1=12.5;
int i1=f1;
This assigning of variable f1 float value to i1 int type will result in loss of decimal value of f1. However,
this type type compatibility will not show any type error but it might give a warning “possible loss of data”.
2. Expression compatibility
Consider following example
int num=5/2;
cout<< num;
Here in the above example the result will be 2 because The actual result of 5/2 is 2.5 but
because of incompatibility there will be loss of decimal value
3. Parameter compatibility
Due to incompatibility when we pass the values from calling to called function in type of actual parameter and formal parameters loss of data occurs.
For example
void show(int num)
{
cout << ”num=” << num;
}
void main()
{
show(5.2);
}
|
Here output will be num=5 due to incompatibility in actual and formal parameter type.