As we have just seen in the previous lesson, the processor can only perform operations on variables of the same type. In programming, we may have to perform calculations on variables of different types or expect a result of different types. For example, it be necessary to obtain a float as a result of the division of two integers two integers:
int a = 5;
int b = 10;
printf ("5 / 10 = %f\n", a / b);
The above example does not work as expected:
When the type conversion is performed automatically by the compiler without the conversion being mentioned explicitly in the code, we speak of implicit type conversion . It is a temporary conversion, because the type conversion is only done during the instruction where it is invoked. Here is an example of the division of a float by an integer. The compiler is forced to convert one of the two variables into the other type. Here, the integer is converted into a float:
float a = 5;
int b = 10;
// An implicit type conversion happens
printf ("5 / 10 = %f\n", a / b);
If you don't know the automatic conversion rules, or if you are not sure of the result, use explicit type conversions.
The explicit type conversion consists in stipulating in the code the variable concerned
and the destination type. Here, we will explicitly convert the variables
a
and b
from type int
to type double
. As before the conversion
is temporary. It is only effective during the instruction where it is invoked:
After the calculation, the variables will become int
again.
We speak about type cating. In the example below,
we perform a cast on the variables a
and b
as double
:
int a = 5;
int b = 10;
// Perform cast on variable a and b during the calculation
printf ("%f", (double)a / (double)b);
To perform a cast, simply specify the destination type before
the variable in parentheses. The variables a
and b
are casted as doubles.
The explicit type conversion can be performed on
(float)a
(long double)12
(float)(2+3)
The program below calculates the average of 3 grades, but the result displayed is not what we expected. Correct the program to obtain the unrounded average using an explicit type conversion:
int grade1=12;
int grade2=14;
int grade3=15;
// Change this line to get the exact result
// Use an explicit type conversion
float average = (grade1 + grade2 + grade3)/3;
// Display the average
printf ("Average = %f", average);
Using the original code from exercise 1, correct the program using now an implicit type conversion:
int grade1=12;
int grade2=14;
int grade3=15;
// Change this line to get the exact result
// Use an implicit type conversion
float average = (grade1 + grade2 + grade3)/3;
// Display the average
printf ("Average = %f", average);
What is an implicit type conversion?
What is an explicit type conversion?
What is the syntax that allows an explicit type conversion?
We can perform a cast on ...
Let's consider the following variables:
int a = 3;
int b = 6;
Correct this calculation so that the result is accurate:
float x = (a + b) / 5;