Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Implicit Type Conversion | Other Data Types and Concepts
C++ Data Types
course content

Contenido del Curso

C++ Data Types

C++ Data Types

1. Introduction
2. Numerical Data Types
3. Text Data Type
4. Other Data Types and Concepts

bookImplicit Type Conversion

In C++, type conversion happens all the time.
It can be either implicit conversion that is performed automatically by the compiler. Or explicit conversion, where you explicitly convert the types in code. This chapter will focus on implicit conversion.

Here is one simple example where implicit type conversion occurs:

cpp

main

copy
1234567
#include <iostream> int main() { int num = 6.5; std::cout << num << std::endl; }

In the example, 6.5, a floating-point number, is implicitly converted to int (which is done by removing the decimal part).

Implicit type conversion happens when the type of a variable does not match the type compiler expects (e.g., when we assign a value to int, the compiler expects an integer number, and it will perform a type conversion if it receives something else)

Let's look at the following visualization:

  • Red arrows stand for data loss. For example, if we convert float to long (or int), we will lose the decimal part;
  • Green arrows stand for no data loss. For example, we can safely convert int to long, and the result is the same;
  • Yellow arrow in conversion from long (or int) to float (or long) means that sometimes we get a data loss due to insufficient precision of float (or long).
cpp

main

copy
1234567891011
#include <iostream> #include <iomanip> int main() { int num_int = 123456789; float num_float = num_int; std::cout << std::setprecision(10); std::cout << num_float << std::endl; }

One more example of implicit type conversion in C++ is the +, -, *, / operations. They should be performed on variables with the same data type. If it's not the case – C++ implicitly does the type promotion. For example, int / double -> double / double.

One more example where you can meet the implicit type conversion is conditions. For example, the if statement.

It expects the condition to be a bool type. But thanks to implicit type conversion, we can pass other data types as conditions. Here is an image showing how they are converted to bool:

Note

Empty string and empty list are also converted as true.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 6
We're sorry to hear that something went wrong. What happened?
some-alt