3

consider the following example:

typedef enum {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday} Day;
void DoSomething(Day day){
//some code
}

The problem is that the following code complies: DoSomething(74). So how can I check in DoSomething that my parameter is really a Day? (relying on numbers won't work because if I change my enum like that Sunday=7 .... ,I want it to work too, and checking if(day==Sunday || day ==...) looks inefficient).

1

4 Answers 4

5

The short answer is you can't.

The long answer is you can try to put a "minimum" and a "maximum" member, and check that the value falls in the range between the two... or some other similar trick.

2
  • But if you check day >=0 && day <=6 and then change your enum to Sunday=7... , your code won't works.
    – Michael
    Commented Apr 4, 2014 at 9:56
  • @Sefi: You would do enum {First,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Last} Day; and then check if First < day && day < Last.
    – user541686
    Commented Apr 4, 2014 at 10:45
1
typedef enum {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday, Last} Day;
void DoSomething(Day day){
   // if day < Last ...
}
1
  • 1
    If you're going to go this route, I think it's much better to just have Last (without an assignment) and then check using day < last, since that makes the construct less brittle. Otherwise you can add something after Saturday and fail to update Last, causing breakage.
    – unwind
    Commented Apr 4, 2014 at 9:50
0

You could put a switch statement in your DoSomething.

switch(day){
case Day.Monday:
     // something
    break
...
default: 
    // ignore or something
0

If you write DoSomething(74) statement in your code modern compiler generate warning saying DoSomething expect enum but integer is passed.

But if you are passing a value from user input where any value can be passed to DoSomething() then you will have to take care as other advised.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.