Type Casting
Learn what type casting is and how it works.
In C++, type casting refers to converting one data type to another. This can be necessary when performing operations involving different data types or when data needs to fit into a specific type.
Mathematical operations and data types
When performing mathematical operations, the result’s data type is determined by the types of the operands. The rule is simple: the result’s data type is the larger of the two operands’ types. For example:
Adding a
float
and adouble
: The result will be adouble
sincedouble
is larger thanfloat
.Adding a
float
and anint
: The result will be afloat
since afloat
is larger than anint
.Adding two integers: The result will be an integer.
Multiplying an
int
and adouble
: The result will be adouble
, as it is larger than anint
data type.
The compiler automatically handles these conversions, ensuring that the result is stored in the appropriate type.
Data types
Let’s look at the illustration below.
The illustration organizes data types by size and precision, with smaller data types on the left and larger ones on the right. The arrow demonstrates how type casting works during data conversion:
Left to right: Converting from a smaller data type (e.g.,
int
...