Menu

Type conversion in C Programming

  • Type conversion is the process of converting predefined datatypes into another datatypes in a particular expression.
  • Type conversion is used when constants and variables of different datatypes are mixed in an expression, inorder for getting the correct result.
  • Consider the following code,
            int num1=10;
            int num2=6;
            float result;
            result=num1/num2;
            printf("%d",result);
    
  • Type conversion is broadly divided into two types
    1. Implicit Type conversion
    2. Explicit Type conversion

Implicit Type conversion

  • Implicit Type conversion is the automatic type conversion done by the compiler.
  • If the operands are of different types, the lower type is converted to higher type before the operation proceeds.
  • Consider the following code,
          int num1=10;
          int num2=20.5;
          int sum;
          sum=num1+num2;
          printf("%d",sum);
    
  • In the above code snippet, num1 is assigned as 10 and num2 assigned as 20.5 with datatype int. Here we will get the output as 30. That is the floating value 20.5 will automatically converted to int and it is done by the compiler.

Explicit Type conversion

  • Explicit type conversion is also known as type casting.
  • In Type casting, the user is responsible for the conversion of one type of datatype to another specific datatype.
  • The generel form of Type casting is (type-name)expression
  • type-name may be any of standard data types in c such as int, float, char.
  • expression may be a constant, variable or expression.

Examples

  1. sum=int(num1+num2)
  2. sum=int(num1)+num2
  • In the first example, the result of num1 and num2 will be converted to integer.
  • In the second example,num1 will be converted to integer and num2 will be added to them.
  • consider the following code snippet,
            int num1=5,num2=2;
            float result;
            result=float(num1/num2);
            printf("%f",ans);
    
  • Here it will produce the result 2.5