Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi and enum

Tags:

delphi

Does Delphi have an analog of enum in C?

like image 615
Hacker Avatar asked Mar 04 '10 12:03

Hacker


2 Answers

In addition to the positive responses that are focused on the parallels, there are

Some restrictions:

1. Anonymous enumerations are not supported in Delphi.

So you have to translate

enum { SOME_CONSTANT = 42 };

into

const
  SOME_CONSTANT = 42

… which is, by the way, a better wording for your actual intent. But unfortunately, this can be translated back into something different. At least C++Builder 6 translates it like this in the auto-generated *.hpp file:

static const Shortint SOME_CONSTANT = 0x2A;

2. Explicit enum values were added with Delphi 6.

The feature of explicitly adding values to enumerators was introduced with Delphi 6. So you have to switch to normal constants, see this answer to How to create an enum with explicit values in Delphi 5 for more.

3. Finally, a restriction of C:

In C, enumerations are just compile-time constants that are implicitly converted into int as needed. This is basically where the support ends. Delphi has a stronger typing but provides information about the valid range and also iteration, see this snippet:

procedure TForm1.Button1Click(Sender: TObject);
type
  TMyEnum = (meOne, meTwo, meThree);
var
  v: TMyEnum;
  txt: String;
begin
  for v := Low(TMyEnum) to High(TMyEnum) do
    txt := txt + IntToStr(Integer(v)) + ' ';
  ShowMessage(txt)
end;
like image 144
Wolf Avatar answered Oct 25 '22 09:10

Wolf


Yes, Delphi has the following enumerated type construction:

type
  TDigits = (dgOne, dgTwo, dgThree <etc>);

Also, like in C, each symbol of an enumerated type may have a specified value, like this:

type
  TDigits = (dgOne = 1, dgTwo, dgThree <etc>);
like image 26
da-soft Avatar answered Oct 25 '22 09:10

da-soft