Cpp - Implicit Type Conversions

Introduction

C++ can mix arithmetic types in a single expression.

The operands of an operator can belong to different types.

In general the "smaller" type will be converted to the "larger" type.

Integer Promotion

Integer promotion is first performed for any expression:

  • bool, char, signed char, unsigned char, and short are converted to int
  • unsigned short is converted to int if the int type is greater than short, and to unsigned int in all other cases.

The boolean value false is converted to 0 and true is converted to 1.

Given a char variable c, the values of c and 'a' in the expression

c < 'a' 

will be converted to intbefore being compared. 

Example

int i = 100; 
long lg = i + 50; // Result of type int is converted to long. 

long lg = 0x654321;  
short st; 
st = lg;         //0x4321 is assigned to st. 

int i = -2;  
unsigned int ui = 2; 
i = i * ui; // i.e. -4  is stored in i. 

double db = -4.567; 
int i;  
unsigned int ui; 
i = db;          // Assigning -4. 
i = db - 0.5;    // Assigning -5. 
ui = db;         // -4 is incompatible with ui. 

double d = 1.23456789012345; 
float f; 
f = d;           // 1.234568 is assigned to f. 

Exercise