Type casting means converting a value from one type to another. Some conversions happen on their own, and others happen only when you ask for them with a cast. C and C++ both support casting. The examples below use C++, and the C-style syntax works in C too.
Automatic conversions
The compiler converts values for you in many situations, most often when you assign a value to a variable of a different type or mix two types in one expression.
int whole = 7;
double asDouble = whole; // becomes 7.0
double measured = 9.8;
int truncated = measured; // becomes 9, because the fraction is dropped
Converting a typical 32-bit int to a double keeps its value exactly. Converting a double to an int drops everything after the decimal point. Some compilers warn about the second conversion when extra warnings are turned on.
Integer division is a common trap
int total = 17;
int count = 4;
double wrong = total / count; // 4.0
double right = static_cast<double>(total) / count; // 4.25
Both operands in total / count are integers, so C++ performs integer division and drops the fraction before the result is stored as a double. Casting one operand to double first makes the division work with decimals.
Explicit casts
An explicit cast asks for a conversion directly. C uses the (type) syntax:
double price = 9.99;
int dollars = (int)price; /* 9: the fraction is dropped */
C++ also has named casts, which are easier to search for and make the intent clearer. static_cast covers most everyday conversions between related types:
int letterCode = static_cast<int>('A'); // 65 on ASCII systems
char letter = static_cast<char>(66); // 'B' on ASCII systems
Can I convert a char to an int? Yes. A char is an integer type, so the conversion keeps its numeric value, as the 'A' example shows.
Casting a number to bool gives true for any nonzero value:
int n = 5;
bool hasValue = static_cast<bool>(n); // true
Brace initialization blocks some conversions
Brace initialization refuses conversions that could lose data:
int a{3.5}; // compile error: narrowing conversion from double to int
int b = 3.5; // compiles; b is 3
Which cast should you use?
- In C, the
(type)syntax is the explicit cast you have. - In C++, prefer
static_castfor conversions between related types. It is easier to find in code, and it allows less than the(type)syntax, which can quietly do several kinds of cast. - Where you can, declare the value with the right type from the start, so no cast is needed.
Common mistakes
- Dropping decimals by assigning a
doubleto anint. - Dividing before casting, which gives an integer result.
- Casting to a type that is too small for the value, which can change the value or lose information.
Casts are useful, but each one is a place where the value might change. Write them on purpose, and check the result when the numbers matter.