'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?



Solution 1:[1]

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.

Solution 2:[2]

There is no more elegant way than to add one extra enumerator. But you can add it to the end of the list, so it will be more useful:

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

You need to initialize your variable, but that's the good practice anyway. The extra benefit is that your code can use the SIZE enumerator to determine the number of enumerators before it.

// initialize
Element element = Element::SIZE;
...
if ( element == Element::SIZE )
 // this means that the variant value is undetermined
...
for ( int i = 0; i < Element::SIZE; i++ )
 // do something for each meaningful enumerator
...
printf ( "number of enumerators in enum Element: %i\n", Element::SIZE );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 iiibs