Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-devel / 2024-02

Question about "Default()"

3 messages · 3 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Martin Frb

https://www.freepascal.org/docs-html/rtl/system/default.html

Default is a compiler intrinsic: it returns for every type T a default value. In essence, this is a block of memory that is zeroed out. It can be used to correctly initialize any type, and more importantly, a managed type. It also works using a generic type template.

But zero isn't always a valid value => so how can it be used to initialize a type where that is invalid.

The below will runtime error "invalid enum value". (And also, in the past, I saw it pointed out countless times, that setting an enum to an ordinal value that is not matching any of its members does not have a defined behaviour).

So is that a bug in Default?
Or is the documentation wrong "any type"? (it contradicts itself anyway "zeroed" "any type")
Or ...?

program Project1;
type
   //tt = 3..5;
   tt = (e1=3, e2=5,e3=7);
var a: tt;
begin
   a := Default(tt);
   writeln(a);
   readln;
end.

Reply by email

Michael Van Canneyt
to Martin Frb: https://www.freepascal.org/docs-html/rtl/system/default.html But zero isn't always a…
Martin Frb wrote 17 lines
https://www.freepascal.org/docs-html/rtl/system/default.html > Default is a compiler intrinsic: it returns for every type T a default > value. In essence, this is a block of memory that is zeroed out. It can be > used to correctly initialize any type, and more importantly, a managed > type. It also works using a generic type template. But zero isn't always a valid value => so how can it be used to initialize a type where that is invalid. The below will runtime error "invalid enum value". (And also, in the past, I saw it pointed out countless times, that setting an enum to an ordinal value that is not matching any of its members does not have a defined behaviour). So is that a bug in Default? Or is the documentation wrong "any type"? (it contradicts itself anyway "zeroed" "any type")

I have amended the documentation to say that a block of zeroes is not necessarily a correct value, and have given 3 examples of types where it can go wrong.

Michael.

Reply by email