-5

Can somebody give me an example where we really need an enum to be a parameter in function?

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • 3
    How do you differentiate "need" and "really need"? – Drew Dormann Sep 02 '12 at 08:07
  • 2
    I 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 Answers3

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
0

The function setColor in button, need to get parameter color, which sould be enum.

LeeNeverGup
  • 1,096
  • 8
  • 23