Can somebody give me an example where we really need an enum to be a parameter in function?
Asked
Active
Viewed 1.2k times
-5
-
3How do you differentiate "need" and "really need"? – Drew Dormann Sep 02 '12 at 08:07
-
2I think you would better help yourself by asking a different question. The reason for using an enum as a function parameter is the same as the reason for using an enum anywhere else in your code. – Ben Cottrell Sep 02 '12 at 08:21
-
1"really need" is too strong; you never do, but using them can make your code clearer, easier to maintain, and less bug-prone (especially in C++) – Clifford Sep 02 '12 at 10:51
3 Answers
5
Besides making code clearer, in C++ it enforces at compile time that a function only work with one out of a set of possible values:
namespace Foo
{
enum Bar { A, B, C };
void foo(Bar b) { .... }
void foo2(int i) { /* only ints between 0 and 5 make sense */ }
}
int main()
{
Foo::Bar b = Foo::A;
Foo::foo(b); // OK
Foo::foo(245); // Compile-time error!
Foo::foo2(6); // Compiles, triggering some run-time error or UB
}

juanchopanza
- 223,364
- 34
- 402
- 480
-
True of C++ but not of C which does not enforce type checking of enum types. A C compiler may however issue a warning, but may not do so as described here: http://stackoverflow.com/questions/8597426/enum-type-check-in-c-gcc – Clifford Sep 02 '12 at 10:49
-
@Clifford thanks for pointing that out. I hadn't realised the question was about two different languages, which is nonsense. – juanchopanza Sep 02 '12 at 11:13
-
"nonsense" may be a bit strong - the languages share some identical syntax and are interoperable, it is perhaps naive but not unreasonable to assume identical semantics for the same syntax - the gotcha being they are not identical. – Clifford Sep 02 '12 at 12:00
2
There is no need for enums, but they make software more readable. Example:
void write( const std::string&, bool flush );
And now the calling side:
write( "Hello World", true );
If an enum had been used, on the calling side it becomes more clearly what the second parameter means:
enum flush_type { flush, no_flush };
void write( const std::string&, flush_type flush );
and again the calling side:
write( "Hello World", flush );

Torsten Robitzki
- 3,041
- 1
- 21
- 35
-
1Not really, the use of enumerations limits what you can pass as function argument to values of the enumeration. – juanchopanza Sep 02 '12 at 08:11
-
@juanchopanza: Exactly. What should the function do with an unanticipated value? Enums help clarify what the function has been designed to do. – Pontus Gagge Sep 02 '12 at 08:14
-
@PontusGagge and may force a compiler error, as in the example in my answer. – juanchopanza Sep 02 '12 at 08:15
-
0
The function setColor in button, need to get parameter color, which sould be enum.

LeeNeverGup
- 1,096
- 8
- 23
-
Note that every enum is equivalet to consts in the machine language – LeeNeverGup Sep 02 '12 at 08:13