C/C++

Enumerations(enum) in C++ With Program Examples

Enumerations

Enumerations(enum)

Enumerations(enum)-An enumeration is a language type introduced with the C language, which has migrated almost untouched into the C++ language. Enumerations are not true types, as classes are. You can’t define operators for enumerations, nor can you change the way in which they behave. As with pre-processor commands, the enumerations(enum) command is really more of a syntactical sugar thing, replacing constant values with more readable names. It allows you slightly better readability, but does nothing to change the way your code works. Enumerations(enum) allow you to use meaningful names for values, and allow the compiler to do better type checking. The downside of an enumeration is that because it is simply a syntactical replacement for a data value, you can easily fool the compiler by casting invalid values to the enumerated type. The general syntax of enumeration is given below:



enum <name> {

value1[=number],

value2,

value3,

. . .

valuen

} EnumerationTypeName;

where the <name> field is the enumerations(enum) type we are creating, the value parameters are the individual values defined in the enum, and number is an optional starting point to begin numbering the enumerated

values.

For example:

enum color {

Red = 1.

Green = 2.

Yellow

} ColorType;

Programming explanation:

In this example, every time the compiler encounters ColorType::Red in our application, it understands the value to be 1, Green would be 2, and Yellow 3 (because the numbers are consecutive unless you specify otherwise).

If enumerations(enum) actually do not change the logic of your code, why would you bother with them? The primary reason for enumerations(enum) s is to improve the readability of your code. To illustrate this, here I

show you a simple technique involving enum s you can use to make your code a little safer to use, and a lot easier to understand.


“Note: Enumerations(enum) s are a great way to have the compiler enforce your valid values on the programmer. Rather than checking after the fact to see whether the value is valid, you can let the compiler check at compile-time to validate that the input will be within the range you want. When you specify that a variable is of an enumerated type, the compiler ensures that the value is of that type, insisting that it be one of the values in the enum  list.”

You might notice that enumerations(enum) s are a simpler form of the Range validation class. Enumerations(enum) s are enforced by the compiler, not by your code, and require considerably less effort to implement than a Range checking class. At the

same time, they are not as robust. Your mileage may vary, but enumerations(enum) s are usually used more for readability and maintenance concerns than for validation.

Implementing the Enumerations(enum)  Class:

An enumerations(enum)  is normally used when the real-world object it is modeling has very simple, very discrete values. The first example that immediately leaps to mind is a traffic light, which has three possible states: red, yellow, and green. In the following steps, let’s create a simple example using the traffic light metaphor

to illustrate how enum work and can be used in your application.


Example how to make traffic lights in c++ programming using Enumerations(enum):

#include <iostream>

#include <stdio.h>
typedef enum
{
Red = 0,
Yellow,
Green
} TrafficLightColor;
int ChangeLight( int color )
{
switch ( color )
{
case 1: // Red
printf("Changing light to RED. Stop!!\n");
break;
case 2: // Yellow
printf("Changing light to YELLOW. Slow down\n");
break;
case 3: // Green
printf("Changing light to GREEN. Go for it\n");
break;
default:
printf("Invalid light state. Crashing\n");
return -1;
}
return 0;
}
int ChangeLightEnum( TrafficLightColor color )
{
switch ( color )
{
case Red: // Red
printf("Changing light to RED. Stop!!\n");
break;
case Yellow: // Yellow
printf("Changing light to YELLOW. Slow down\n");
break;
case Green: // Green
printf("Changing light to GREEN. Go for it\n");
break;
}
return 0;
}



Testing the EnumerationClass

  • Add the following code to test the enumerations(enum) and validate that it is working properly: This code could easily be moved to a separate file. It is placed in one file simply as a convenience. The code illustrates why enumerations(enum) s are more type-safe than basic integer types, and why you might want to use enumerations(enum) s over the basic types.
int main(int argc, char **argv)
{
int clr = -1;
ChangeLight( clr );
TrafficLightColor c = Red;
ChangeLightEnum( c );
return 0;
}
  •  Save the file and close the code editor.
  • Compile and run the application with your favorite compiler on your favorite operating system.

If you have done everything right, you should see the following output on the shell window:

Invalid light state. Crashing

Changing light to RED. Stop!!


enumerations(enum) Final Program:

#include <iostream>

#include <stdio.h>
typedef enum
{
Red = 0,
Yellow,
Green
} TrafficLightColor;
int ChangeLight( int color )
{
switch ( color )
{
case 1: // Red
printf("Changing light to RED. Stop!!\n");
break;
case 2: // Yellow
printf("Changing light to YELLOW. Slow down\n");
break;
case 3: // Green
printf("Changing light to GREEN. Go for it\n");
break;
default:
printf("Invalid light state. Crashing\n");
return -1;
}
return 0;
}
int ChangeLightEnum( TrafficLightColor color )
{
switch ( color )
{
case Red: // Red
printf("Changing light to RED. Stop!!\n");
break;
case Yellow: // Yellow
printf("Changing light to YELLOW. Slow down\n");
break;
case Green: // Green
printf("Changing light to GREEN. Go for it\n");
break;
}
return 0;
}
int main(int argc, char **argv)
{
int clr = -1;
ChangeLight( clr );
TrafficLightColor c = Red;
ChangeLightEnum( c );
return 0;
}

Output:

Invalid light state. Crashing
Changing light to RED. Stop!!


Enumerations(enum)  Declaration in other Programming languages:

enumerations(enum) in C#

  • In C# the enumerations(enum) data type can be defined as:
enum Cardsuit { Clubs, Diamonds, Spades, Hearts };

enumerations(enum) in GO

  • In Go uses the iota keyword to create enumerated constants.
type ByteSize float64

const (

    _           = iota // ignore first value by assigning to blank identifier

    KB ByteSize = 1 << (10 * iota)

    MB

    GB

)



Java

  • IN Java The J2SE version 5.0 of the Java programming language added enumerated types whose declaration syntax is similar to that of C:
  enum Cardsuit { CLUBS, DIAMONDS, SPADES, HEARTS };

  ...

  Cardsuit trump;

Perl

  • In Perl Dynamically typed languages in the syntactic tradition of C (e.g., Perlor JavaScript) do not, in general, provide enumerations(enum) But in Perl programming the same result can be obtained with the shorthand strings list and hashes (possibly slices):
my @enum = qw(Clubs Diamonds Hearts Spades);

my( %set1, %set2 );

@set1{@enum} = ();          # all cleared

@set2{@enum} = (1) x @enum; # all set to 1

$set1{Clubs} ...            # false

$set2{Diamonds} ...         # true

 Ruku

  • In Rakudoes provide enumerations(enum) . There are multiple ways to declare enumerations(enum) s in Raku, all creating a back-end Map.
enum Cat <sphynx siamese bengal shorthair other>; # Using "quote-words"

enum Cat ('sphynx', 'siamese', 'bengal', 'shorthair', 'other'); # Using a list

enum Cat (sphynx => 0, siamese => 1, bengal => 2, shorthair => 3, other => 4); # Using Pair constructors

enum Cat (:sphynx(0), :siamese(1), :bengal(2), shorthair(3), :other(4)); # Another way of using Pairs, you can also use `:0sphynx`


Rust

  • In Rust Though Rust uses the enum keyword like C, it uses it to describe tagged unions, which enums can be considered a degenerate form of. As such, Rust’s enums are much more flexible and can also store struct types, etc.
enum Message {

    Quit,

    Move { x: i32, y: i32 }, // anonymous struct

    Write(String),

    ChangeColor(i32, i32, i32),

}

Swift

  • In Swift Enumerations(enum) s can also define initializers to provide an initial case value and can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality.
enum CardSuit {

     case clubs

     case diamonds

     case hearts

     case spades

}

Python

  • In Python An enum module was added to the Python standard library in version 3.4.
from enum import Enum

class Cards(Enum):

    clubs = 1

    diamonds = 2

    hearts = 3

    spades = 4



Fortran

  • In Fortranonly has enumerated types for interoperability with C; hence, the semantics is similar to C and, as in C, the enum values are just integers and no further type check is done. The C example from above can be written in Fortran as

 

enum, bind( C )

                           enumerator :: CLUBS = 1, DIAMONDS = 2, HEARTS = 4, SPADES = 8

  end enum

Vb.net

  • Enumerated datatypes in Visual Basic (up to version 6) and VBAare automatically assigned the “Long” datatype and also become a datatype themselves:
Zero-based

Enum CardSuit

   Clubs

   Diamonds

   Hearts

   Spades

End Enum




Sub EnumExample()

    Dim suit As CardSuit

    suit = Diamonds

    MsgBox suit

End Sub


“Note:Whenever you use an integer value for input to a function — and that input value is intended to be mapped directly to a real-world set of values — use an enum  rather than a simple integer. Remember to use meaningful names for your enum  values to help the application programmers understand what values they are sending to your functions and methods. This will save you time and effort and will make your code more self-documenting, which is always a good thing.”

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button