Type Conversions

Learn about converting one data type to another through the implicit and the explicit type conversions.

There are two kinds of type conversion we need to talk about: automatic or implicit type conversion and explicit type conversion.

Implicit type conversion

The operators we have looked at can deal with different types. For example, we can apply the addition operator + to int as well as double values. It’s important to understand how operators deal with different types that appear in the same expression. There are rules in C that govern how operators convert different types, to evaluate the results of expressions.

For example, when a floating-point number is assigned to an integer variable in C, the decimal portion of the number gets truncated. On the other hand, when an integer value is assigned to a floating-point variable, the decimal part of the number is assumed as .0.

This sort of implicit or automatic conversion can produce nasty bugs that are difficult to find, especially when performing multiplication or division using mixed types, e.g., integer and floating-point values. Here is some example code illustrating some of these effects:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy