Sunday, 6 November 2011

What is operator promotion? in C programming language

What is operator promotion?

If an operation is specified with operands of two different types, they are converted to the smallest type that
can hold both values. The result has the same type as the two operands wind up having. To interpret the rules,
read the following table from the top down, and stop at the first rule that applies.




The following example code illustrates some cases of operator promotion. The variable f1 is set to 3 / 4.
Because both 3 and 4 are integers, integer division is performed, and the result is the integer 0. The variable
f2 is set to 3 / 4.0. Because 4.0 is a float, the number 3 is converted to a float as well, and the result is
the float 0.75.

#include <stdio.h>
main()
{
float f1 = 3 / 4;
float f2 = 3 / 4.0;
printf(“3 / 4 == %g or %g depending on the type used.\n”,
f1, f2);
}

Cross Reference:

II.11: Are there any problems with performing mathematical operations on different variable
types?
II.13: When should a type cast be used?

No comments:

Post a Comment