Now, let’s give an example of explicit conversion:
In this situation, we are splitting the pieces of pizza with our friend. We are trying to figure out how many pieces each person should get.
Both operands are integers, so the result will be an integer. There are two ways we can fix this. First, we can add .0 to the 2. This works, but it will not always work. For example, we could have this:
Print this out and see that the result of the double is actually 8, not 8.5.
Let’s assume that the second operand is given to us as an integer and we cannot change it for some reason. The only solution is to use an explicit cast:
This explicitly casts the value of slices to be a double.
Now, when you output the data, it should be 8.5.
The important thing to know here is that the cast does not affect the original value of the variable. The casting is actually just another operator. Think of it as a unary operator that does not change the value of the variable.
The value of the variable is first given, and then that value is changed to a double, but the original variable stays the same. Once you define a variable as a certain type, you’re stuck with it.
It’s important to think of the casting as a unary operator. That means that it only works on one operand. Which operand? Is it this:
or is it:
It’s actually the second one. It only affects the thing to the direct right.
You can cast an entire expression using parenthesis, so the first one is completely valid. The only problem is that the result will still be 8. That’s because we divide two ints by one another and get 8, and then we cast 8 to a double, which stays 8.
Because of this potential area of confusion, I recommend you try to avoid casting a large expression that is in parenthesis unless you know exactly how it is going to work.
What will this output?
This program illustrates that even if one of the operands is floating point, the entire expression does not use floating point arithmetic. In the case with the variable d, the 25/2 evaluates to 14, then * 2 evaluates to 24.0. Both printf()’s output the same thing.
Remember that the decimal is always truncated, never rounded. So even if some division ended with .99999, it would just delete the .99999 and not round up.
Ready to learn more? Read the next blog on our first quiz covering the past content!