Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can I do with an enum variable?

When I declare a enum variable like this:

enum paint_colors { RED, GREEN, BLUE, ...} colors;

is the colors variable useful? If so, what can I do with it?

Thanks in advance.

like image 750
drigoSkalWalker Avatar asked Mar 23 '10 18:03

drigoSkalWalker


People also ask

What is the use of enum variable?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

What can you do with enums?

An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties.

Why is enum not good?

They Lack Accountability. To be clear, it's a mistake to assume consensual non monogamy is void of commitment. It's not simply informing your casual hookup of your other casual hookups. For a lot of people, it's being communicative to their partner of what they're doing with their friend with benefits or boyfriend.


1 Answers

Internally, an enum is treated as an integer that can only hold a limited range of values. In this case, the constants RED, GREEN, BLUE, ... will be defined and will be equal to 0, 1, 2, ... (respectively). The variable colors can be used anywhere an int can be used. You can use operators like ++ to iterate through the list of colors. The only difference between declaring enum paint_colors colors and int colors is that the enumerated variable can should only be assigned one of the enumerated constants.

This gives you several benefits over using #define to create a series of constants and using a normal int for colors. First, some debuggers can detect that colors is an enumerated type and will display the name of the enumerated constant instead of a numeric value.

More importantly, this can add an additional layer of type checking. It is not required by the C standard, but some compilers check and make sure that values assigned to a variable of enumerated type correspond to one of the enumerated constants.

Mentally, you can almost think of this is similar to saying:

#define RED    0
#define GREEN  1
#define BLUE   2
typedef int paint_colors;
paint_colors colors;

The variable is treated like an int, but explicitly giving it a different type helps to clarify what the variable is and what it is used for.

like image 103
bta Avatar answered Oct 19 '22 17:10

bta