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.

Sign up to request clarification or add additional context in comments.

2 Comments

But if you check day >=0 && day <=6 and then change your enum to Sunday=7... , your code won't works.
@Sefi: You would do enum {First,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Last} Day; and then check if First < day && day < Last.
1
typedef enum {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday, Last} Day; void DoSomething(Day day){ // if day < Last ... } 

1 Comment

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

You could put a switch statement in your DoSomething.

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.