egsoftweb@gmail.com
 facebook.com/egsoftweb

Type Conversion & Casts in C

 c tutorials |  Admin

Type Conversion:

When constants and variables of different types are mixed in an expression, they are all converted to the same type. The compiler converts all operands up to the type of the largest operand, which is called “type promotion”. First, all char and short int values are automatically elevated to int. This process is called “integral promotion”. (In C99, an integer promotion may also result in a conversion to unsigned int) Once this step has been completed, all other conversions are done operation by operation in the following type promotion order.

 

long double

double

float

unsigned long

long

unsigned int

int

char

Type Promotion Order:

 

There is one additional special case: If one operand is long and the other is unsigned int, and if the value of the unsigned int cannot be represented by a long, both operands are converted to unsigned long.

Once these conversion rules have been applied, each pair of operands is of the same type, and the result of each operation is the same as the type of both operands.

  

For example:

// example type conversion

#include <stdio.h>

int main()

{

     char c = `c`; /* ascii value of c is 99 */

     int i = 5;

     float f =7.7f;

     double d = 3.12334;

 

     /*let we print the expression

     ((c / i) + (f*d) - (f + i)) in different formats

     */

     printf("%d", ((c / i) + (f*d) - (f + i)));

     printf("\n");

     printf("%f", ((c / i) + (f*d) - (f + i)));

     getchar();

     return 0;

}

 

/* output

 

396452324

30.349718

*/

 

/*

Here in the expression ((c / i) + (f*d) - (f + i)),

(c/i) converted into int, (f*d) converted in to double

& (f+i) converted in float.The result of int, double &

float is double and so the final result is in double.

*/

  

Casts:

We can force an expression to be of a specific type by using a cast. General form of a cast is

(type) expression

where type is a valid data type. For example, to cause the expression x/2 to evaluate to type float, we write

(float) x/2

 

Casts are technically operators. As an operator, a cast is unary and has the same precedence as any other unary operator.

 

//example using cast

#include <stdio.h>

int main()

{

     int i = 159;

     printf("half of i is %f", (float)i / 2);

     getchar();

     return 0; 

}

 

/*

here without the cast (float), only an integer

division would have been performed. The cast

ensures that the fractional part of the answer

is displayed.

*/

References:

[1] C The Complete Reference 4th Ed, Herbert Schildt.