programming-languageslanguage-theoryalgolalgol68

Static types and conversions


Suppose I have an algol-like language, with static types and the following piece of code:

a := b + c * d;

where a is a float, b an integer, c a double and d a long. Then, the language will convert d to long to operate with c, and b to double to operate with c*d result. So, after that, the double result of b+c*d will be converted to float to assign the result to a. But, when it happens?, I mean, do all the conversions happens in runtime or compile time?

And if I have:

int x; //READ FROM USER KEYBOARD.
if (x > 5) {
    a:= b + c * d;
}
else {
    a := b + c;
}

The above code has conditionals. If the compiler converts this at compile time, some portion may never run. Is this correct?


Solution

  • You cannot do a conversion at compile-time any more than you can do an addition at compile time (unless the compiler can determine the value of the variable, perhaps because it is actually constant).

    The compiler can (and does) emit a program with instructions which add and multiply the value of variables. It also emits instructions which convert the type of a stored value into a different type prior to computation, if that is necessary.

    Languages which do not have variable types fixed at compile-time do have to perform checks at runtime and conditionally convert values to different types. But I don't believe that is the case with any of the languages included in the general category of "Algol-like".