I have an enum:
enum myenum{
typeA,
typeB,
typeC
} myenum_t;
Then, a functions is to be called with an enum parameter:
Yes.
Let the compiler do its work, don't cast int
to an enum
type and you should be good.
Can't you also do something like
enum myEnum {typeA,typeB, typeC};
int myFunction (myEnum arg1) {
if (arg1 >= typeA && arg1 <= typeC) {
// do work here
} else {
printf("invalid argument!");
}
return 0;
}
Enumerations in C++ already have stronger types than in C.
Take the following simple program:
#include <iostream>
enum E
{
A,
B
};
void f(E e)
{
}
int main()
{
f(1);
}
Using the GCC compiler I will get a this error:
enum.cpp: In function ‘int main()’: enum.cpp:15: error: invalid conversion from ‘int’ to ‘E’ enum.cpp:15: error: initializing argument 1 of ‘void f(E)’
So as you can see the enumeration members are already checked.
If you want even stronger type checking, and have a C++11 capable compiler, you can use even stronger type checking for enums, see http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations.
Unfortunately there isn't a simple way to do it language level (at least with C
), you just have to make sure you are using only variables defined via enum
.
Although you could enable one of the following compiler warnings together with -Werror
:
-Wswitch
-Wswitch-default
-Wswitch-enum
This makes build fail if one of the enums is missed inside switch.
A common convention for this is to do something like this:
typedef enum {
typeA,
typeB,
typeC,
num_types
} myenum_t;
Then you can check for (t < num_types)
.
If you subsequently add more enums, e.g.
typedef enum {
typeA,
typeB,
typeC,
typeD,
typeE,
num_types
} myenum_t;
then num_types
is automatically updated and your error checking code doesn't need to change.
One trick I've used in the past:
enum foo {FIRST_FOO, BAR, BLETCH, BLURGA, BLAH, LAST_FOO};
and then check to see if your value is > FIRST_FOO && < LAST_FOO
1.
Of course, this assumes that there are no gaps between your enumeration values.
Otherwise, no, there's no good method to do what you're asking (at least in C).
6.7.2.2 Enumeration specifiers
...
3 The identifiers in an enumerator list are declared as constants that have typeint
and may appear wherever such are permitted.109) An enumerator with=
defines its enumeration constant as the value of the constant expression. If the first enumerator has no=
, the value of its enumeration constant is0
. Each subsequent enumerator with no=
defines its enumeration constant as the value of the constant expression obtained by adding1
to the value of the previous enumeration constant. (The use of enumerators with=
may produce enumeration constants with values that duplicate other values in the same enumeration.) The enumerators of an enumeration are also known as its members.