How to check if an enum variable is valid?

前端 未结 7 1021
执笔经年
执笔经年 2021-01-11 11:07

I have an enum:

enum myenum{
  typeA,
  typeB,
  typeC
} myenum_t;

Then, a functions is to be called with an enum parameter:



        
相关标签:
7条回答
  • 2021-01-11 12:09

    You could use a bitwise enum:

    enum myEnum {
        typeA = 1 << 0;
        typeB = 1 << 1;
        typeC = 1 << 2;
    }
    
    int myFunction(myEnum arg1)
    {
        int checkVal = typeA | typeB | typeC;
    
        if (checkVal & arg1)
        {
            // do work here;
        }
        else
        {
            printf("invalid argument!");
        }
    
        return 0;
    }
    

    Excuse me, it seems I have read the question wrong.

    It appears what you want to do is determine if you have a proper value passed in, not some random invalid option. In that case, the most logical option is this:

    if (arg1 < typeA || arg1 > typeC)
        printf("invalid argument");
    

    This is, of course, assuming you don't set manual values for your enum, which, is quite rare unless using bitwise enums.

    0 讨论(0)
提交回复
热议问题