Explicit type conversion in C | Casting in C


Explicit type conversion in C | Casting in C

It is the way to convert the output of an arithmetic expression into a data type specified by the programmer. It is basically used to change implicit conversion.

The syntax of casting is:

(Type) Expression

type refers to any valid data type of C language in which we want to convert the output of an expression.

Expression refers to an valid arithmetic expression of C language which is to be converted into a specific data type. 

There are three types  of explicit conversion.

a. Checked

Before the conversion is performed, a run-time check is done to see if the destination type can hold the source value. If not, an error condition is raised.

b. Unchecked

No check is performed. If the destination type cannot hold the source value, the result is undefined.

c. Bit pattern

The raw bit representation of the source is copied and it is re-interpreted according to the destination type.

Program to demonstrate explicit conversion.
int main()
int a,b;
float c;
c=(float)a/b;         /*Line 10*/
In line 10 of above program, a and b are of int type so result of a/b should be of int type i.e. 3 which has been assigned to variable c which is also of int type. So c will contain 3.

Best Books of C

Lesson tags: casting in c, data type conversion in c, explicit type conversion in c, user defined data conversionin c
Back to: C Programming Language