Search code examples
language-designcompiler-constructiontype-promotioncompiler-development

Compiler Type Promotion of Right Hand Side expressions automatically in an Assignment Statement


Why does a compiler not type promote all evaluations of expressions in the right hand side of an assignment expression to at least the left hand sides type level?

e.g. "double x = (88.0 - 32) * 5 / 9" converts to Celsius from Fahrenheit correctly but... "double x = (88.0 - 32) * (5 / 9)" will not.

My question is not why the second example does not return the desired result. My question is why does the compiler not type promote the evaluation of (5/9) to that of a double.


Solution

  • Why does a compiler not type promote all evaluations of expressions in the right hand side of an assignment expression to at least the left hand sides type level?

    Very good question. Actually,let's suppose for sometime that the compiler does this automatically. Now, taking your example :-

    double x = 88.0 - 32 * 5 / 9
    

    Now the RHS part of this assignment can be converted into double completely for all tokens(lexemes) in several of ways. I am adding some of them :-

    1. 88.0 - 32 * (double)(5 / 9)
    2. 88.0 - 32 * 5 / 9 // default rule
    3. 88.0 - (double)(32 * 5) / 9
    4. Individually type-casting to double every token which doesn't seem to be a double entity.
    5. Several other ways.

    This turns to combinatorial problem like "In how many ways a given expression can be reduced to double(whatever type)?"

    But, the compiler designers wouldn't take such a pain in their *** to convert each of the tokens to the desired highest type(double here) considering the exhaustive use of memory. Also it appears like an unnatural rationale behind it doing this way for no reason because users could better perform the operation by manually giving some hints to the compiler that it has to typecast using the way coded by the user.

    Being everything automatic conversion is not going to yield you the result always, as sometimes what a user wants may not be achieved with this kind of rationale of automatic type promotion, BUT, the vice-versa of type-promoting will serve in a much better way as is done by the compilers today. Current rule for type-casting is serving all the purposes correctly, though with some extra effort, but, FLAWLESSLY.