C++ Data Type Implicit Conversions

Introduction

Some values can be implicitly converted into each other.

This is true for all the built-in types.

We can convert char to int, int to double, etc.

Example:

int main() /*w  w  w.  j  a v  a  2 s  .  c om*/
{ 
    char mychar = 64; 
    int myint = 123; 
    double mydouble = 456.789; 
    bool myboolean = true; 

    myint = mychar; 
    mydouble = myint; 
    mychar = myboolean; 
} 

We can also implicitly convert double to int.

However, some information is lost, and the compiler will warn us about this.

This is called narrowing conversions:

int main() 
{ 
    int myint = 123; 
    double mydouble = 456.789; 

    myint = mydouble; // the decimal part is lost 
} 

When smaller integer types such as char or short are used in arithmetic operations, they get promoted/converted to integers.

This is referred to as integral promotion.

For example, if we use two chars in an arithmetic operation, both get converted to an integer, and the whole expression is of type int.

This conversion happens only inside the arithmetic expression:

int main() 
{ 
    char c1 = 10; 
    char c2 = 20; 

    auto result = c1 + c2; // result is of type int 
} 



PreviousNext

Related