Expression evaluation – type conversions in C

Arithmetic operations work only on the same types. When two types are dissimilar, type conversion takes place. This follows the following order:

1. (long double, anything) -> long double
2. (double, anything except 1.) -> double
3. (float, anything except 1. and 2.) -> float

i.e., if any of the operands is long double, the other is promoted to long double. Similarly for double, and so on.

Next, arithmetic operations do not happen on characters and short ints – these get promoted to ints thus:
unsigned char -> unsigned int
signed char -> int
unsigned short int ->unsigned int
short int -> int

After these integer promotions, we follow the following promotion rules:
4. (long int, unsigned int) -> long int or unsigned long int, depending on whether long int can hold all values of the unsigned int.
5. (long int, anything except 1, 2, 3, or 4) ->long int
6. (unsigned int, int) -> unsigned int
7. (int, int)

Basically we are going by size here, just in case you hadn’t observed that. Remember, this is done by the compiler – so you may not notice it .. until sudden side effects crop up. Be aware of what is happening when you write an arithmetic expression. For more details, see this.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s