C++ Enumerations

  • An enumeration is a user-defined type that consists of a set of named integer constants that are known as enumerators.

  • Enum is a user defined data type where we specify a set of values for a variable and the variable can only take one out of a small set of possible values. We use enum keyword to define a Enumeration.

  • For example : Let us define the enumeration.

    • enum Fruits { Orange, Apple , Banana , Pineapple , Strawberry};

  • The name of the enumeration is Fruits. Orange, Apple , Banana , Pineapple and Strawberry are values of type Fruits. By default, Orange is 0, Apple is 1 and so on. You can change the default value of an enum element during declaration.

  • You can change the default by specifying a starting value for your enum as in the following example.

    enum Fruits { Orange = 1, Apple , Banana , Pineapple , Strawberry };

  • When you create an enumerated type, only the frame for the variable is created. You can create variables of enum type as follows.

  • enum Fruits myfruit;

  • Here, a variable myfruit of type enum Fruits is created.

  • An enum variable takes only one value out of many possible values. The size of the enum variable is 4 bytes.The size is four bytes because the enum is stored as an int.

  • Let us see what the output of the following code will be:

    • enum Cars { Benz = 1, BMW, Audi, Ferrari, Tesla}; 

      Cars mycar; 

      mycar = Audi; 

      cout << mycar << endl;

  • When this code snippet is executed we see that Audi is not printed but the number 3 is printed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: