Type Casting - C Programming

Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float. Casting allows you to make this type conversion explicit, or to force it when it wouldn’t normally happen.

Type conversion in c can be classified into the following two types:

1. Implicit Type Conversion

When the type conversion is performed automatically by the compiler without programmers intervention, such type of conversion is known as implicit type conversion or type promotion.

int x;
for(x=97; x<=122; x++)
{
    printf("%c", x);   /*Implicit casting from int to char thanks to %c*/
}

2. Explicit Type Conversion

The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion. The explicit type conversion is also known as type casting.

Type casting in c is done in the following form:

(data_type)expression;

where, data_type is any valid c data type, and expression may be constant, variable or expression.

For example,

int x;
for(x=97; x<=122; x++)
{
    printf("%c", (char)x);   /*Explicit casting from int to char*/
}

The following rules have to be followed while converting the expression from one type to another to avoid the loss of information:

  1. All integer types to be converted to float.
  2. All float types to be converted to double.
  3. All character types to be converted to integer.

Example

Consider the following code:

int x=7, y=5 ;
float z;
z=x/y; /*Here the value of z is 1*/

If we want to get the exact value of 7/5 then we need explicit casting from int to float:

int x=7, y=5;
float z;
z = (float)x/(float)y;   /*Here the value of z is 1.4*/

Next - Storage Classes


Discussion

Read Community Guidelines
You've successfully subscribed to Developer Insider
Great! Next, complete checkout for full access to Developer Insider
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.