[fpc-devel] Types and Casts handling in FreePascal Expressions
Hans-Peter Diettrich
DrDiettrich1 at aol.com
Wed Apr 20 15:47:54 CEST 2011
Pocket MicroTechnics Support schrieb:
> Hello,
> I have just a little question about expressions and types/cast management
> in FreePascal.
>
> if I have a mixed expression with:
> i, j, n : byte
> k : word
>
> n := i + k - j;
IMO the compiler converts operands to the "bigger" (wider) of the
involved operand types, for every single operator. Possible overflows
usually are ignored, i.e. the coder would have to cast one operand to an
type, that allows to compute even intermediate results without
overflows. Only the *detection* of actual overflows can be enforced by
the overflow check compiler directive.
Furthermore the compiler is free in the order of evaluation, i.e. might
here produce word(i-j)+k (not sure about the concrete FPC implementation
and optimization options).
Finally a range check can be enforced, before the calculated value is
stored in (truncated to the type-size of) the result variable.
> What I mean, does the compiler handle types locally by casting at each
> node, and force the cast at assignment node?
> or does it do like C compiler, i.e. check the LValue at left of the
> assignement, take its type, and cast each BinOp node to this type
I doubt that a C compiler behaves as you describe. Consider the obvious
case of boolean expressions, where it doesn't make sense to convert the
*operands* of "if (a<b)" into something like a bit or byte, only because
the result of the comparison can be represented by a single bit or CPU
status flag. A compiler typically is allowed only to *widen" the operand
types automatically, but not to narrow them down. AFAIR implicit
downcasts can occur with assignment operators (in C), where the
intermediate result is truncated to the size of the assignment variable,
and evaluation continues with the type of that variable.
DoDi
More information about the fpc-devel
mailing list