Search code examples
ctype-promotion

Promotion Order in C-like Languages


We know that types get promoted. For example, if you write:

int i = 2;
double d = 4.0;
double result = i / d;

. . . then the int will get promoted to a double, resulting in 0.5. However, I wasn't able to find any information on what happens if promotion and evaluation order conflict (it's also surprisingly difficult to Google). For example:

int i = 2;
int j = 4;
double d = 1.0;
double result = d * i / j;

In this example, the value depends on when promotion happens. If i gets promoted before the division, then the result will be 0.5, but if the result of i / j gets promoted, then integer division happens and the result is 0.0.

Is the result of what happens well defined? Is it the same in C++ and other C-derived languages?


Solution

  • Is the result of what happens well defined?

    Yes.

    Is it the same in C++ and other C-derived languages?

    For C++ - yes. But "C-derived languages" is not that well defined, so it is hard to answer.

    The order of evaluation of

    d * i / j
    

    is

    (d * i) / j
    

    So, first i gets promoted to double due to d * i.

    Then, the result (double) has to be divided by j, so j gets promoted to double. So there are two promotions.

    However, for

    d + i / j
    

    the order of operations is different. First, i / j division is done using integer arithmetics, and then the result is promoted to double. So there is only one promotion.