David
David

Reputation: 477

Enumerated Type: Limit to number of items?

Is there a limit in Delphi to the number of items you can have in an enumerated type? I need to create an enumerated type that might have several hundred items, and want to make sure there is not a limit at 255 items for example.

type 
  TMyType = (mtOne, mtTwo, mtThree, ..., mtThreeHundred);

Upvotes: 6

Views: 3618

Answers (4)

splash
splash

Reputation: 13327

I found a maximum of 65535 items in a german Delphi book.

After some digging in the documenation I found the respective section:

Enumerated Types

An enumerated type is stored as an unsigned byte if the enumeration has no more than 256 values and the type was declared in the {$Z1} state (the default). If an enumerated type has more than 256 values, or if the type was declared in the {$Z2} state, it is stored as an unsigned word. If an enumerated type is declared in the {$Z4} state, it is stored as an unsigned double-word.

So in fact there should be a possible maximum of 4294967295 ($FFFFFFFF) items.

Upvotes: 5

vcldeveloper
vcldeveloper

Reputation: 7489

Yes enums in Delphi can have more than 256 items. You won't have problem with them, but if you are going to use set types, you should take note that sets can have 256 elements at most.

Upvotes: 0

Barry Kelly
Barry Kelly

Reputation: 42152

I believe the theoretical limit is 2^32 items; but in practice, RTTI generation is normally the limit, as RTTI can't exceed 65535 bytes to store everything, including the names of the enumeration elements; the names are stored in UTF-8, so it's not too bad.

On the other hand, enumerations with explicit values for the elements don't have full RTTI, so you can evade the limit that way. Here's a program which creates a source file with 500,001 enumeration elements, which itself compiles:

var
  i: Integer;
begin
  Writeln('type');
  Writeln('  E = (');
  for i := 1 to 500000 do
    Writeln('  x_', i, ' = ', i, ',');
  Writeln('x_last);');
  Writeln('begin');
  Writeln('end.');
end.

The output of this program takes some time to compile with dcc32 because the Delphi compiler uses a hash table with only 32 buckets for checking for enumeration identifier duplicates, and a hash table with only 256 buckets for file-level scope, which (in the absence of {$SCOPEDENUMS ON}) is where enumeration identifiers are added.

Upvotes: 6

Chris Thornton
Chris Thornton

Reputation: 15817

Try it and see? It should just take a few minutes to write a loop that will build your type statement as long as you want. Output with a messagebox (which can be copied to the clipboard with ctrl+c), paste back into Delphi, and you're all set.

Upvotes: 1

Related Questions