Conteúdo do Curso
C++ Data Types
C++ Data Types
Implicit 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:
main
#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).
- Red arrows stand for data loss. For example, if we convert
float
tolong
(orint
), we will lose the decimal part; - Green arrows stand for no data loss. For example, we can safely convert
int
tolong
, and the result is the same; - Yellow arrow in conversion from
long
(orint
) tofloat
(orlong
) means that sometimes we get a data loss due to insufficient precision offloat
(orlong
).
main
#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
.
Obrigado pelo seu feedback!