1

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?

rici
  • 234,347
  • 28
  • 237
  • 341
Tomás Juárez
  • 1,517
  • 3
  • 21
  • 51

1 Answers1

2

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".

rici
  • 234,347
  • 28
  • 237
  • 341
  • But the compiler knows the variables types, does it matter the value in the variable? – Tomás Juárez Jan 29 '17 at 21:20
  • 1
    @TomiSebastiánJuárez: The compiler can *emit code which does the conversion* because it knows what the variables type is. But it cannot *do the conversion* unless it also knows the value in the variable. It is no different from `a+a`. If the compiler knew that the vaule in `a` were `2`, it could do the addition and replace the expression with `4`. Otherwise, all it can do is emit code to do the addition. – rici Jan 29 '17 at 21:30