Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define an "Unknown" or "NULL" value in an enum

I am defining a custom typedef Elements as follows....

typedef enum  {
    Ar,
    Cl,
    F,
    He,
    H,
    Kr,
    Ne,
    N,
    O,
    Rn,
    Xe
} Element;

I want to check a variable of type Element has not been set (essentially just check for a NULL value). As far as I can tell the only way to do this is to add an extra line

.... {
      unknown = 0,
      Ar,
      F,
...etc

Am I right or is there a more elegant way to do this?

like image 414
Nick Jones Avatar asked Sep 26 '12 00:09

Nick Jones


People also ask

Can enum have null value?

Enum types cannot be nullable.

How do you define an enum variable?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Can we initialize enum to null?

All enum types are value types and the different members are also derived from member types (the allowed types are byte , sbyte , short , ushort , int , uint , long , or ulong - as documented). This means that members of an enumeration cannot be null .

Can we declare variable in enum?

Enumerations are similar to classes and, you can have variables, methods, and constructors within them.


1 Answers

Yes, you should include an "unknown" value. Basically an enum is just an int. If you don't define any constants in the declarations (as in your first code sample) the first option will be set to 0 and the default value.

An alternative might be to set the first option to 1. This way the value 0 won't be defined and you can check for that manually.

typedef enum {
    Ar = 1,
    Cl,
    F,
    He,
    H,
    Kr,
    Ne,
    N,
    O,
    Rn,
    Xe
} Element;


if (myElement) {  // same as  if (myElement != 0)
    // Defined
} else {
    // Undefined
}

But I would opt for an explicitly defined "unknown" value instead.

like image 192
DrummerB Avatar answered Oct 06 '22 06:10

DrummerB