Implicit and explicit type conversion in C++ are two sides of the same coin. An implicit conversion happens quietly when the compiler decides that a value of one type is acceptable where another is expected. An explicit conversion happens when you ask for it with static_cast. The first one is convenient and dangerous, the second one is deliberate and safe, and the whole topic is really about not letting a number change meaning without you noticing.
The previous lesson in this module covered "How Do Variables, const and constexpr Work?", and the next lesson in this module is about "How Do Arithmetic Operators and Precedence Work?".
Where implicit conversion happens
C++ converts a value to a different type whenever the conversion is well defined and the result can be represented. The common places are arithmetic expressions, assignment, function arguments and return values.
#include <iostream>
int main() {
int guests = 4;
double extra_portions = 1.5;
double total = guests + extra_portions; // guests promoted to double
int truncated = guests + extra_portions; // result narrowed back to int
int widened = extra_portions; // double converted to int
std::cout << "total: " << total << "\n";
std::cout << "truncated: " << truncated << "\n";
std::cout << "widened: " << widened << "\n";
return 0;
}The arithmetic promotion rules are worth stating plainly, because they explain the results above.
- If either operand is a double, a long double or a float, then the other one is converted to that type and the result is floating point.
- Otherwise the operands are promoted to int if they need to be, and the operation is integer arithmetic.
- The result is then converted to the type of the destination.
So 4 plus 1.5 is 5.5, and assigning 5.5 to an int keeps only the whole part. That is not a bug, it is the rule, and it is exactly where a lot of recipe scaling code goes quietly wrong.
Explicit conversion with static_cast
An explicit conversion says "yes, I know these are different types, and I mean it". The static_cast is the modern way to write one. It reads clearly, it works for arithmetic and pointer conversions, and the compiler rejects the conversions that make no sense.
#include <iostream>
int main() {
double cups_of_flour = 3.75;
int whole_cups = static_cast<int>(cups_of_flour);
double rounded = static_cast<double>(whole_cups);
std::cout << "whole cups: " << whole_cups << "\n";
std::cout << "back to double: " << rounded << "\n";
std::cout << "rounded up: " << static_cast<int>(cups_of_flour + 0.999999) << "\n";
return 0;
}The conversion happens exactly where you asked for it, and nothing else changes type as a side effect.
The old C-style cast, (int) cups_of_flour, still compiles. Avoid it. It can perform conversions that static_cast refuses, which makes it both harder to read and harder to search for.
Narrowing conversions and lost information
A narrowing conversion is one that cannot represent every value of the source type. Putting a double into an int is narrowing. Putting a long long into an int on a 32-bit platform is narrowing. Braced initialisation rejects narrowing at compile time, and that is why it is worth using.
#include <iostream>
int main() {
// double scale = 2.5; // would not compile with braces
double scale = 2.5;
int lost = scale; // implicit, truncates toward zero
int explicit_loss = static_cast<int>(scale);
std::cout << "implicit: " << lost << "\n";
std::cout << "explicit: " << explicit_loss << "\n";
unsigned int big = 4000000000U;
int wrapped = static_cast<int>(big); // value does not fit
std::cout << "wrapped: " << wrapped << "\n";
return 0;
}Truncation always goes toward zero, so 2.9 becomes 2 and minus 2.9 becomes minus 2, and never minus 3. If you need rounding rather than truncation, use std::round from <cmath> before you convert.
The signed to unsigned trap
This one catches even experienced programmers. When you compare a signed value with an unsigned value, C++ converts the signed value to unsigned first. A negative number therefore becomes an enormous positive number.
#include <iostream>
int main() {
int remaining = -1;
unsigned int stock = 5;
// The comparison the compiler actually performs after
// converting the signed value to unsigned.
unsigned int remaining_wrapped = static_cast<unsigned int>(remaining);
std::cout << "mixed comparison: " << (remaining_wrapped < stock) << "\n";
std::cout << "remaining as unsigned: " << remaining_wrapped << "\n";
return 0;
}The comparison says false, because minus 1 became 4294967295 when it was converted. The fix is to make the types match before you compare, or to keep the counts non-negative by design.
The integer division trap
Dividing two integers performs integer division and it throws the fractional part away. This is the single most common bug in a scaling program that happens to look right for small numbers.
#include <iostream>
int main() {
int batches = 7;
int guests = 3;
std::cout << "integer division: " << batches / guests << "\n";
std::cout << "true division: " << static_cast<double>(batches) / guests << "\n";
std::cout << "remainder: " << batches % guests << "\n";
return 0;
}Seven batches shared between three guests is two whole batches each with one left over. The integer division reports 2, and the modulo reports the leftover 1.
A conversion checklist
Before you convert, ask three questions.
- Which direction am I going? Widening from int to double is safe. Narrowing the other way loses information.
-
Is the conversion implicit? If the compiler chose it, then you did not. Add a
static_castso that the intent is explicit and searchable. - Does the value fit? A negative count, a fraction, or a number past the destination's maximum are all reasons to stop and reconsider.
Quick reference
- Implicit conversions happen at arithmetic, assignment, arguments and returns.
- An int and a double mix by promoting to double, and two integers use integer arithmetic.
- Use
static_castto make a conversion explicit and local. - Narrowing truncates toward zero and it can lose data. Braced initialisation rejects it at compile time.
- Mixing signed and unsigned in a comparison converts the negative value to a huge positive one.
- Dividing two integers discards the fraction, so cast one operand to double first.
- Prefer
std::roundto truncation when you need rounding rather than chopping.
Try it yourself: take a recipe that says "scale by 2.5" and write it both ways, once relying on the implicit conversion and once with an explicit static_cast. Then change the serving count to an odd number and watch the integer division result differ from the mathematical one. Finally, add a negative quantity and see how the unsigned comparison misbehaves.