C Type Conversion
The last lesson gave each value a type. Type conversion turns a value from one type into another, and a cast is a conversion you write on purpose.
An int becomes a double
whole holds 7, and copy holds the same value as a double. The print line shows 7 with a decimal point.
#include <stdio.h>
int main() {
int whole = 7;
double copy = whole;
printf("%f\n", copy);
return 0;
}Double loses its decimal part
price holds 9.99, and whole holds the same value as an int. The part after the decimal point is gone.
#include <stdio.h>
int main() {
double price = 9.99;
int whole = price;
printf("%d\n", whole);
return 0;
}A cast changes the type
The cast (int) turns price into an int on purpose. The print shows 9, so the decimal part is gone, and this time the change is written down.
#include <stdio.h>
int main() {
double price = 9.99;
int whole = (int) price;
printf("%d\n", whole);
return 0;
}Example
#include <stdio.h>
int main() {
int total = 7;
double exact = (double) total;
double price = 9.99;
int whole = (int) price;
printf("%f\n", exact);
printf("%d\n", whole);
return 0;
}Key points
- Type conversion turns a value from one type into another.
- C does an implicit conversion on its own when the types differ.
- An int stored in a double keeps its value and gains a decimal point.
- A double stored in an int loses the part after the decimal point.
- A cast is a change of type written on purpose, like (double) total.
- A cast sits in front of a value, inside round brackets.
- A cast to double gives a whole number a decimal point.
- A cast to int drops the part after the decimal point, on purpose.
The first cast turns total into a double, so the print shows 7 with a decimal point. The second cast turns price into an int, so the print shows 9 without the decimal part.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line turns the int value in total into a double?