Saturday 23 December 2017

Integer Promotion or Type casting in C Language - Geeks4Coding



Type casting in C

 A type cast is basically a conversion from one type to another. There are two types of type conversion:

Implicit Type Conversion Also known as ‘automatic type conversion’ and also called as “Widening”.
  • Done by the compiler on its own, without any external trigger from the user.
  • Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid lose of data.
  • All the data types of the variables are upgraded to the data type of the variable with largest data type. 

         unsigned int -> long -> unsigned -> 

         bool -> char -> short int -> int ->

         long long -> float -> double -> long double

  • It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long long is implicitly converted to float).

Example of Type Implicit Conversion:


#include<stdio.h>
int main()
{
int x = 10; // integer x
char a = 'a'; // character c

// a implicitly converted to int. ASCII
// value of 'a' char is 97
x = x + a;

// x is implicitly converted to float
float b = x + 1.0;

printf("x = %d, z = %f", x, z);
return 0;
}

 

Output:
 

x = 107, b = 108.000000
 

Explicit Type Conversion– This process is also called type casting also called as “Narrowing” and it is user defined. Here the user can type cast the result to make it of a particular data type.
 

The syntax in C:

            (data type) expression

Type indicated the data type to which the final result is converted.
 

#include<stdio.h>

int main()
{
double b = 1.2;

// Explicit conversion from double to int
int add = (int)b + 1;

printf("add = %d", add);

return 0;
}

 

Output:
 

add = 2
 

Advantages of Type Conversion

  • This is done to take advantage of certain features of type hierarchies or type representations.
     
  • It helps us to compute expressions containing variables of different data types.

No comments:

Post a Comment

Thank you for your Time. Keep Learning

Geeks4Coding

Contributors

Popular Posts