Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 199
  • Last Modified:

Can you use a floating point value in an enum?

Building a big project so I can't test the theory atm. Has anyone tried it?

enum foo {NEWFOUNDLAND_STANDARD_TIME = -3.5}

if not what's a good workaround?

-Sandra
0
Sandra-24
Asked:
Sandra-24
1 Solution
 
imladrisCommented:
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.
0
 
nesrohtretepCommented:
Alternatively, use defines  - they can be any type you want:

#define NEWFOUNDLAND_STANDARD_TIME -3.5

 - Peter
0
 
tinchosCommented:
I would recommend that instead of defines, use

const float NEWFOUNDLAND_STANDARD_TIME = -3.5;



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

Tincho
0
 
Sandra-24Author Commented:
Not to mention defines make a mess of the global namespace
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now