D Programming Language 2.0

- Comments
- D
- Search
- Downloads
- Home

Last update Wed Oct 17 15:41:32 2007

# Enums - Enumerated Types

    EnumDeclaration:
    	enum Identifier EnumBody
    	enum EnumBody
    	enum Identifier : EnumBaseType EnumBody
    	enum : EnumBaseType EnumBody

    EnumBaseType:
    	Type

    EnumBody:
    	;
    	{ EnumMembers }

    EnumMembers:
    	EnumMember
    	EnumMember ,
    	EnumMember , EnumMembers

    EnumMember:
    	Identifier
    	Identifier = AssignExpression

Enums are used to define a group of related integral constants.

If the enum Identifier is present, the EnumMembers are declared in the scope of the enum Identifier. The enum Identifier declares a new type.

If the enum Identifier is not present, then the enum is an anonymous enum, and the EnumMembers are declared in the scope the EnumDeclaration appears in. No new type is created; the EnumMembers have the type of the EnumBaseType.

The EnumBaseType is the underlying type of the enum. It must be an integral type. If omitted, it defaults to int.

    enum { A, B, C }	// anonymous enum

Defines the constants A=0, B=1, C=2 in a manner equivalent to:

    const int A = 0;
    const int B = 1;
    const int C = 2;

Whereas:

    enum X { A, B, C }	// named enum

Define a new type X which has values X.A=0, X.B=1, X.C=2

Named enum members can be implicitly cast to integral types, but integral types cannot be implicitly cast to an enum type.

Enums must have at least one member.

If an Expression is supplied for an enum member, the value of the member is set to the result of the Expression. The Expression must be resolvable at compile time. Subsequent enum members with no Expression are set to the value of the previous member plus one:

    enum { A, B = 5+7, C, D = 8, E }

Sets A=0, B=12, C=13, D=8, and E=9.

### Enum Properties

    .init			First enum member value
    .min			Smallest value of enum
    .max			Largest value of enum
    .sizeof			Size of storage for an enumerated value

    For example:

    X.min			is X.A
    X.max			is X.C
    X.sizeof		is same as int.sizeof

### Initialization of Enums

In the absence of an explicit initializer, an enum variable is initialized to the first enum value.

    enum X { A=3, B, C }
    X x;		// x is initialized to 3

Copyright © 1999-2007 by Digital Mars, All Rights Reserved | Page generated by Ddoc. | Comments