![]() |
VOOZH | about |
Type conversion is the process of converting a value from one data type to another compatible data type. It allows different types of data to work together in expressions, assignments, and function calls.
65 75
Explanation: In the example, (int)c explicitly converts the character 'A' to its ASCII value 65. During the addition i + c, the character is implicitly converted to an integer before the operation is performed.
C++ supports two types of type conversion:
Implicit type conversion (also called coercion) is performed automatically by the compiler whenever a value needs to be converted to a compatible type. It commonly occurs when:
i = 107 c = a f = 108
Explanation: In the example, the character 'a' is automatically converted to its ASCII value (97) before being added to the integer variable.
bool when used in conditional expressions.Note: Implicit conversions may cause data loss, sign changes, or overflow when converting between incompatible types.
Explicit type conversion, also known as type casting, is performed manually by the programmer to convert a value from one type to another.
In C++, it can be done by two ways:
1. C Style Typecasting
This method is inherited by C++ from C. The conversion is done by explicitly defining the required type in front of the expression in parenthesis. This can be also known as forceful casting.
(type) expression;
where:
2
Explanation: The value of x is explicitly converted from double to int before being used in the expression.
Note: C-style casts are generally less safe because they do not clearly indicate the kind of conversion being performed.
2. C++ Style Typecasting
C++ provides dedicated cast operators that make conversions safer and more explicit.
Types of C++ Cast Operators
2
Explanation: static_cast<int>(x) explicitly converts the value of x to an integer before it is used.
Although type conversion is useful, improper conversions can introduce errors: