C++ Programming

Enumerations(enum) in C++ With Programming Examples

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. Enumeration(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,

. . .

value n

} EnumerationTypeName;

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

values.


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

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 enumerations(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 enumerations(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 enumeration (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 enumerations(enum) s work and can be used in your application.

Example:

#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 source-code 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:

Output:

Invalid light state. Crashing

Changing light to RED. Stop!!


Enumerations(enum)  Declaration in other Programming languages:

  • In C# the enumerations(enum) data type can be defined as:
enum Cardsuit { Clubs, Diamonds, Spades, Hearts };
  • 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

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

  ...

  Cardsuit trump;
  • In Perl Dynamically typed languages in the syntactic tradition of C (e.g., Perlor JavaScript) do not, in general, provide enumeration(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
  • In Rakudoes provide enumerations(enum) s. 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`


  • In Rust Though Rust uses the enumkeyword 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),

}


  • 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

}
  • 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
  • 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



  • 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 enumeration (enum)  rather than a simple integer. Remember to use meaningful names for your enumerations(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.”

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

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

Back to top button