[fpc-devel] About typecasts and the documentation

Martin Frb lazarus at mfriebe.de
Sat Feb 8 20:25:51 CET 2014


http://www.freepascal.org/docs-html/ref/refse67.html#x124-13400012.4
> In general, the type size of the expression and the size of the type 
> cast must be the same. However, for ordinal types (byte, char, word, 
> boolean, enumerates) this is not so, they can be used interchangeably. 
> That is, the following will work, although the sizes do not match. 

http://www.freepascal.org/docs-html/ref/refse68.html#x125-13500012.5
> A variable can be considered a single factor in an expression. It can 
> therefore be typecast as well. A variable can be typecast to any type, 
> provided the type has the same size as the original variable. 

In the below (first) example "longint(1)" and TFoo have the same size.

The below 2nd example shows that by printing
4
4
1
Surprisingly "SizeOf(1)" is 1, yet the error from the 1st example 
specified that 1 (inside the typecast) was of type longint which should 
give a size of 4.

Yet in the first example they fail. This is not covered by the 
documentation.
The doc even gives examples involving typecasting constant values.
> Byte(’A’) 
given that the doc then goes on, and gives
> Integer(’A’);
that worked via the ordinal value (size does not match), it gives the 
impression that the first example was working under the rule of "same 
size".

But then the doc does not give any clue why same size can not be cast to 
a record.


program project1;
type
TFoo = record b:longint; end;
var
i: longint;
foo: TFoo;
begin
foo := TFoo(i);
foo := TFoo(longint(1)); // project1.lpr(9,8) Error: Illegal type 
conversion: "LongInt" to "TFoo"
foo := TFoo(1); // project1.lpr(10,8) Error: Illegal type conversion: 
"LongInt" to "TFoo"
end.

-------------------------------------
program project1;
type
TFoo = record b:longint; end;
var
i: longint;
foo: TFoo;
begin
foo := TFoo(i);
writeln(SizeOf(TFoo));
writeln(SizeOf(longint(1)));
writeln(SizeOf(1));
readln;
end.





More information about the fpc-devel mailing list