Difference between revisions of "Integer promotion in C"

From Embedded Systems Learning Academy
Jump to: navigation, search
(Created page with "What is integer promotion (32bit machine)? short int and char datatypes take less bytes than corresponding integer (32bit) datatype. These data types are promoted to int32/ui...")
 
 
Line 4: Line 4:
  
 
Let’s take an example:
 
Let’s take an example:
char a =20;
+
char a =20;
char b = 20;
+
char b = 20;
char c=0;
+
char c=0;
c = (a*b/10);
+
c = (a*b/10);
  
 
This will give output as 40.
 
This will give output as 40.
 +
 
But if you look closely when a and b are multiplied it goes to 400, which is out of range for an 8bit char variable. These char variables are promoted to 32bit and expression is evaluated and then answer is truncated to fit to char(8bit).
 
But if you look closely when a and b are multiplied it goes to 400, which is out of range for an 8bit char variable. These char variables are promoted to 32bit and expression is evaluated and then answer is truncated to fit to char(8bit).

Latest revision as of 07:34, 22 December 2016

What is integer promotion (32bit machine)?

short int and char datatypes take less bytes than corresponding integer (32bit) datatype. These data types are promoted to int32/uint32 while operation is performed on them.

Let’s take an example:

char a =20;
char b = 20;
char c=0;
c = (a*b/10);

This will give output as 40.

But if you look closely when a and b are multiplied it goes to 400, which is out of range for an 8bit char variable. These char variables are promoted to 32bit and expression is evaluated and then answer is truncated to fit to char(8bit).