Skip to main content

Section 4.4 Implicit Conversions

As we have seen, the difference between the integer 60 from the floating-point value 60.0 can be confusing. They look like the same number. But they belong to different data types, and thus doing math with them can produce different results.
Adding to the confusion is the fact that C++ will automatically β€œupgrade” an int to a double if you try to store a whole number value into a double variable. This is called implicit conversion. Even worse, if you print a value like 4.0, the unnecessary decimal portion is left off:
Listing 4.4.1.
C++ can do the implicit conversions because any integer can be safely represent as a decimal value. The opposite is not true. There is no way to represent 3.14159 as a whole number without losing information. This code sample demonstrates what happens:
Listing 4.4.2.
Turning a decimal number into an integer can be done by dropping the decimal part. But doing so does change the value you are representing. So the compiler generates a warning. Here in the book, that warning is a fatal error that prevents the program from compiling.

Warning 4.4.1.

Depending on your environment, the compiler may or may not issue a warning for conversions from double to int. And, it may or may not treat that warning as an error and refuse to build the program.
Even if your compiler just warns you and continues. You should consider the code to be a bug. Losing the decimal part of a number because you stored it into an int variable is likely going to be a logic error.

Checkpoint 4.4.1.

Consider the following C++ code:
double a = 7.01;
int b = 7;
Which of the following are safe operations?
  • double c = b;
  • This sets c to 7.0. It is safe because no information is lost.
  • int c = a;
  • This sets c to 7. It is not safe because information is lost.
  • int c = a + b;
  • This sets c to 14. It is not safe because information is lost.
  • double c = a + b;
  • This sets c to 14.01. It is safe because no information is lost.
You have attempted of activities on this page.