Type Conversions

Type Conversions:

Type conversions or type casting is one of the advantages for C Programmers. By typecasting programmer can change the data-type of one variable to another. It is a good practice, converting lower data type to higher data type.

There are two different methods for the typecasting.

1.Implicit conversion:

In this type of conversion, we no need to give the casting operator. This type of conversion is known as implicit/standard conversion.

Ex: Consider the program.

#include<stdio.h>

Int main()

{

int b=32; //integer variable defined

double d; // double data type variable is declared.

d=b; //implicit conversion.

Printf(“implicit conversion %d”,d);

return 0;

}

Output:

Implicit conversion 32.

In this program, we haven’t used any casting operator for the conversion. Here the value in variable ‘a ‘ which was integer type will get promoted to double automatically when the two variables are compatible by the compiler.

There are some rules to convert data types implicitly.

It is shown below

2.Explicit conversion:

In this type of conversion we need to specify the casting operator ’()’, when two data types are incompatible(ie. If you want to convert long to it like that.). This type of conversion is known as explicit conversion.

Ex: Consider the program.

#include<stdio.h>

Int main()

{

 

int b=32; //integer variable defined

 

short d; // short data type variable is declared.

d=(short)b; //explicit conversion.

Printf(“short conversion %d”,d);

return 0;

}

Output:

Explicit conversion 32.

In this program, we have used casting operator for the conversion. Here the value in variable ‘a ‘ which was integer type will get converted to short when the value is copied.

Inbuilt functions for typecasting:

Inbuilt Typecast Functions In C:

There are inbuilt functions are available for type casting in the explicit method. Some of them are shown below.

S.No

Typecast Function

Description

1

atof()

     Convert string to Float

2

atoi()

Convert string to int

3

atol()

Convert string to long

4

itoa()

Convert int to string

5

ltoa()

Convert long to string

En-Query

    Your Name*

    Subject*

    Phone Number*

    Email Address*

    Message*