M
mike3
Hi.
How could I resolve this C++ programming dilemma?
---
enum smth { ZERO, ONE, TWO, MAX }; // not really labeled this way
void f(smth parameter)
{
( ... )
}
( ... )
f(static_cast<smth>(RNG(MAX))); // RNG generates number from 0 to
MAX-1
( ... )
f(TWO); // f is called with fixed constant
( ... )
f(666); // won't work -- good
( ... )
---
Note the marked bit. f() takes the enumerated type smth, so you can't
just stick "666" in there and cause something bad that way, yet I
also need to pass a randomly obtained value from that list, which
requires a cast. Is it considered good practice to use a cast in this
situation? Would it be better to have f() take an "int" or something
like
that and then include an explicit check in there to see if the value
is
outside 0...MAX-1?
Finally, I suppose one could also do this:
int rand(RNG(MAX));
if(rand == ZERO) f(ZERO);
if(rand == ONE) f(ONE);
if(rand == TWO) f(TWO);
This avoids the cast, but seems to introduce a mantainability defect
and
making the code more susceptible to bugs: if one goes and adds more
values to the enum, then must be added here, too (not just in f()),
and
if this is forgotten about... bug!
What should be done here?
How could I resolve this C++ programming dilemma?
---
enum smth { ZERO, ONE, TWO, MAX }; // not really labeled this way
void f(smth parameter)
{
( ... )
}
( ... )
f(static_cast<smth>(RNG(MAX))); // RNG generates number from 0 to
MAX-1
( ... )
f(TWO); // f is called with fixed constant
( ... )
f(666); // won't work -- good
( ... )
---
Note the marked bit. f() takes the enumerated type smth, so you can't
just stick "666" in there and cause something bad that way, yet I
also need to pass a randomly obtained value from that list, which
requires a cast. Is it considered good practice to use a cast in this
situation? Would it be better to have f() take an "int" or something
like
that and then include an explicit check in there to see if the value
is
outside 0...MAX-1?
Finally, I suppose one could also do this:
int rand(RNG(MAX));
if(rand == ZERO) f(ZERO);
if(rand == ONE) f(ONE);
if(rand == TWO) f(TWO);
This avoids the cast, but seems to introduce a mantainability defect
and
making the code more susceptible to bugs: if one goes and adds more
values to the enum, then must be added here, too (not just in f()),
and
if this is forgotten about... bug!
What should be done here?