Can you use a floating point value in an enum?

Sandra-24 used Ask the Experts™
Building a big project so I can't test the theory atm. Has anyone tried it?


if not what's a good workaround?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
No, enums have to be integers.

You could use "scaled" integers. That is, set your enums to the required value times 10. So 10 for 1 hour, 30 for 3 hours and 35 for three and a half hours.

You could then either do everything in "scaled" integers, or, when you need to use them, convert the enum value to a float, and divide by 10.
Alternatively, use defines  - they can be any type you want:


 - Peter

I would recommend that instead of defines, use


From Effective C++ 2nd Edition (Item1)

This Item might better be called "prefer the compiler to the preprocessor," because #define is often treated as if it's not part of the language per se. That's one of its problems.

When you do something like this,

#define ASPECT_RATIO 1.653

the symbolic name ASPECT_RATIO may never be seen by compilers; it may be removed by the preprocessor before the source code ever gets to a compiler.
As a result, the name ASPECT_RATIO may not get entered into the symbol table. This can be confusing if you get an error during compilation involving the use of the constant, because the error message may refer to 1.653, not ASPECT_RATIO.
If ASPECT_RATIO was defined in a header file you didn't write, you'd then have no idea where that 1.653 came from, and you'd probably waste time tracking it down. This problem can also crop up in a symbolic debugger, because, again, the name you're programming with may not be in the symbol table.

The solution to this sorry scenario is simple and succinct. Instead of using a preprocessor macro, define a constant:

const double ASPECT_RATIO = 1.653;

Hope this helps



Not to mention defines make a mess of the global namespace

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial