Type casting in C

 

Typecasting is a way to convert a variable from one data type to another data type. For example if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows:

 

(type _name)  expression

 

Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation

 

#include <stdio.h>

Main()

{

Int sum = 17, count =5;

double mean;

mean = (double) sum / count;

printf(“value of mean : %f \n”, mean);

}

 

When the above code is compiled and executed, it produces the following result:

 

Value of mean ; 3.400000

 

It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.

 

Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are necessary.

 

 

 

 

 

Registration


A password will be e-mailed to you.

Feedback Form

[contact-form-7 id="98" title="Feedback Form"]