Skip to content
Related Articles

Related Articles

Typecasting in C
  • Difficulty Level : Easy
  • Last Updated : 20 Jan, 2021

Typecasting: It is a data type is converted into another data type by the programmer using the casting operator during the program design. In typecasting, the destination data type may be smaller than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion.

There are some cases where if the datatype remains unchanged, it can give incorrect output. In such cases, typecasting can help to get correct output and reduce the time of compilation.

Program 1:

Below is the C program to illustrate the need for typecasting:

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to illustrate the use of
// typecasting
#include <stdio.h>
  
// Function to divide a and b
void division(int a, int b)
{
    float div;
  
    // Division of a and b
    div = a / b;
  
    printf("The result is %f\n", div);
}
  
// Driver Code
int main()
{
    // Given a & b
    int a = 15, b = 2;
  
    // Function Call
    division(a, b);
  
    return 0;
}

chevron_right


Output:



The result is 7.000000

Explanation: Here, the actual output needed is 7.500000, but the result is 7.000000. So to get the correct output one way is to change the data type of a given variable. But correct output can also be done by typecasting. This consists of putting a pair of parentheses around the name of the data type like division = (float) a/b.

Program 2:

Below is the C program to showcase the use of typecasting:

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to showcase the use of
// typecasting
#include <stdio.h>
  
// Function to divide a and b
void division(int a, int b)
{
    float div;
  
    // Typecasting in float
    div = (float)a / b;
  
    printf("The result is %f\n", div);
}
  
// Driver Code
int main()
{
    // Given a & b
    int a = 15, b = 2;
  
    // Function Call
    division(a, b);
  
    return 0;
}

chevron_right


Output:

The result is 7.500000

Explanation: In the above C program, the expression (float) converts variable a from type int to type float before the operation.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :