Friday, 30 April 2021

Implicit and Explicit type conversion | C Language

 Implicit and Explicit type conversion | C Language

Converting one data type into another data type is known as type conversion or typecasting. For example, converting character to number type integer. A waterfall model has been used for type conversion, which guaranteed that no loss of data while conversion.  If you convert the higher data type to a lower data type then data loss will occur, for example, conversion of long to an integer.

Implicit and Explicit type conversion | C Language




Implicit Typecasting

Implicit type casting means conversion of data types without losing its original meaning. This type of typecasting is essential when you want to change data types without changing the significance of the values stored inside the variable.

 

Implicit type conversion happens automatically when a value is copied to its compatible data type. During conversion, strict rules for type conversion are applied. If the operands are of two different data types, then an operand having lower data type is automatically converted into a higher data type. This type of type conversion can be seen in the following example.

Example

#include<stdio.h>

int main()

{

      short x = 10; //initializing variable x with short data type

      int y; //declaring int variable y

      y = x; //implicit type casting

      printf("%d\n", x);

      printf("%d\n", y);

}



Explicit Type casting

The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion. The explicit type conversion is also known as type casting.

The following rules have to be followed while converting the expression from one type to another to avoid the loss of information:

All integer types to be converted to float.

All float types to be converted to double.

All character types to be converted to integer.

Example

#include<stdio.h>

void main()

{

      float a = 1.2;

      //int b  = a; //Compiler may raise error because you will lost .2 . only 1 will be assine to variable b

      int b = (int)a + 1;

      printf("Value of a is %f\n", a);

      printf("Value of b is %d\n", b);

}

 



No comments:

Post a Comment