Typecasting in C

by | Aug 15, 2021 | C

Home » C » Typecasting in C

Introduction

The conversion of a variable from one data type to another data type is referred to as typecasting in C.

For example, converting a float value to an int value.

Conversion of 25.5555 to 25 is done by typecasting.

There are two types of type conversions:

  1. Implicit conversion
  2. Explicit conversion

Implicit Type Conversion in C

Is it possible to add a numeric value and a character value like ‘q+9’?

Yes, ‘q+9’ is a valid expression in C language because we have some numeric value corresponding to every character in C language. And the compiler will automatically convert q to its ASCII value and then add 9 to it. This automatic conversion is known as the implicit conversion of typecasting. The value ‘q’, which is a char type, automatically gets converted into int type by the compiler.

Note: In our programs, if we perform any arithmetic operations consisting of the, character value, their conversion is done automatically from char to int.

Example

#include<stdio.h>
int main()
{
            int x, s;
            char y;
           
            printf("enter a character value: ");
            scanf("%c",&y);
           
            printf("enter an integer value: ");
            scanf("%d",&x);
           
            s=x-y;
            printf("\nDifference: %d",s);
           
            return 0;
}

 

Output

Implicit Type Conversion in C

When the two variables x and y having values ‘25’ and ‘d’ respectively are subtracted, the resultant value is -75 because the ASCII value of ‘d’ is 100 and ‘25-100’ gives -75.

Explicit Type Conversion in C

We, as programmers, have complete control to convert any value from one data type to another.

The type of conversion, when done manually, is called an explicit conversion.

Syntax: (data-type) value;

In the above syntax, ‘value’ will get converted to the data type we want.

Example

Look at the program written below to understand explicit conversion.

#include<stdio.h>
int main()
{
            float a;
            printf("enter a float value:\n");
            scanf("%f",&a);
           
            int b;
            b=(int)a;
            printf("value after type conversion:%d",b);
}

 

Output

Explicit Type Conversion in C

‘a’ is declared as float type, and we converted that into int type.

Alternative Code

The code written below is the same as the code written above, with some changes.

#include<stdio.h>
int main()
{
            float a;
            printf("enter a float value:\n");
            scanf("%f",&a);
            printf("value after type conversion:%d",(int)a);
}

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author