Search code examples
cenumsnulldefaulttypedef

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

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