What is an anonymous Enum in D?

Named enum

Named Enums are defined named constant values and are declared using the enum keyword.

Syntax

enum enum_name {  
   enumeration list 
}

Example

import std.stdio;
// Initialized
enum Cars{ bmw , toyota, rollsroyce, mazda, lexus, subaru, mercedes };
int main(string[] args) {
writefln("Toyota : %d", Cars.toyota);
writefln("Lexus : %d", Cars.lexus);
return 0;
}

Explanation

In the example above, we get some of the enum element’s index.

  • Line 6: We use an int main instead of the normal void main. This is because we are working with the enum, and the string[] args passed will enable the enum's access value in the main function.

  • Line 7 and 8: We print the index of a named enum using the dot notation like the Cars.enum element. Play around with the code to understand it better.

Anonymous enum

An anonymous Enum is an unnamed enum.

Syntax

enum {  
   enumeration list 
}

Example

import std.stdio;
// Initialized
enum { bmw , toyota, rollsroyce, mazda, lexus, subaru, mercedes };
int main(string[] args) {
writefln("Toyota : %d", toyota);
writefln("Lexus : %d", lexus);
return 0;
}

Explanation

We get some of the enum element’s index from the example above.

  • Line 6: We use an int main instead of the normal void main. This is because we are working with the enum, and the string[] args passed will enable the enum's value in the main function.

  • Line 7 and 8: We print the index of an anonymous enum by just calling the name of the enum element. Play around with the code example to understand it better.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources