Type casting in C++ – Part 1

Type casting frequently arises in real life programming. This post concentrates on type conversion of fundamental data types. Type casting is the process of converting from one data type to another. In C++, type casting is automatic in some situations. These are called implicit conversions.

For example
char c = ‘A’;
int ch_code = c;
short s_val = 1024;
int i_val = s_val;
Here the value of “c” is automatically promoted to an int as we are assigning a smaller type into a bigger type. The second case is also similar. This is also called a promotion. There is no truncation in these cases. Other examples of this type include int to float/double, float to double, boolean to int etc…
Implicit type conversion also happen when a bigger type is assigned to smaller type. This might result in truncation/data loss if the source data which cannot fit in the destination type. Some compilers gives a warning when we are using such a conversion. This can be avoided by explicit conversion.
int ch_code = 97;
char ch = ch_code; // no data loss as 97 is within the range of char type; represents the character ‘a’
float pi = 3.14159;
int i_pi = (int)pi; //decimal part is truncated; explicit type conversion
If the truncated integer value is bigger than the integer type, the behavior is undefined.

If a negative integer type is converted to a unsigned type, the resulting value would be 2’s compliment bit representation interpreted as a positive integer.

For example the following code
short x = -32768;
unsigned short y = x;
Assigns a value of 32768 to y. The least value has become the greatest value in this case.

If you are converting an integer to boolean type, all non-zero value will be converted to 1 including negative and positive values which are considered true. 0 is considered false.
int x = -10;
bool b = x; // b is assigned 1, i.e true
x = 10;
b = x; //b is 1 here also
x = 0;
b = x; //b is 0,i.e false

In the later posts, we will look at type conversions between non fundamental data types like pointers and classes.