Course Content
Programming in C
About Lesson

When an operator has operands of different types, they are converted to a common type according to a certain rules. Automatic conversions are those that convert a “narrower” operand into a “wider” one without losing information, such as converting an integer to floating point in an expression like f + i. Expressions that don’t make sense, like using a float as an array subscript, are disallowed. Expressions that might lose information, like assigning a longer integer type to a shorter type or float to int, may draw a warning, but they are not disallowed.

A char is just a small integer, so chars may be freely used in arithmetic expressions. Let’s look at an example function to convert upper case characters into lower case characters, which uses char to int conversion:

int tolower(int c)
{
  if (c >= 'A' && c <= 'Z')
    c = c - 'A' + 'a';
  return c;
}

In general, if a binary operator has operands of different types, the “lower” type is promoted to the “higher” type, before the operation proceeds and the result is of “higher” type.
– If either operand is long double, convert the other to long double.
– Otherwise, if either operand is double, convert the other to double.
– Otherwise, if either operand is float, convert the other to float.
– Otherwise, convert char or short to int.
– Then, if either operand is long, convert the other to long.

Conversion rules are more complicated when unsigned operands are involved. The comparisons between signed and unsigned values are machine-dependent, because they depend on the sizes of various integer types. For example, suppose int is 16 bits and long is 32 bits, then -1L 1UL, because -1L is promoted to unsigned long and thus appears to be a larger positive number.

Conversions take place across assignments; the value of the right side is converted to the type of the left.

Explicit type conversions can be forced in any expression, with a unary operator called cast.

(type name) expression

The above statement converts the expression into the named type.

double a = 2.5;
printf("%d", (int)a);

Here, we type cast double variable a into int, before printing it.

Scroll to Top