Enum vs Const

Introduction

I recently had to review some c++ code written by someone else. The code was well written. It checked for error conditions and did reasonable things if something went wrong. But there was something about it that irked me.

The class CAClass constructor takes a parameter that specifies something of interest to the class, constValue and a pointer to a string. DoSomething() does something relevant based on the parameters passed to the constructor. The class implementation was coded something like this.

There's almost no difference. Any good c++ compiler would compile identical code for both classes.

So what's the difference?

The first class, CAClass, defines a bunch of constant values of interest to itself. CBClass defines the same named constants but it does it as an enum. An enum defines a limited set of valid values and can also be used as a pseudo datatype. Look at the difference in the definitions of the constructors. <PRE lang=c++>CAClass(UINT constValue, LPCTSTR someOtherParameter);
CBClass(constsOfInterestToThisClass constValue, LPCTSTR someOtherParameter);

CAClass can accept any valid UINT value. That's over 4 billion possible values, only 2 of which are of any possible interest to the class. Any valid UINT value outside of 0 or 1 will cause the DoSomething function to raise an exception that other code within your application must handle.

CBClass in contrast will accept only one of the two enum values. Try and pass any invalid constant and the compiler will (should) complain with an error or warning message.

Contrast this <PRE lang=c++>CAClass obj(1000, _T("This is a string"));
obj.DoSomething();

The first example CAClass obj(1000, _T("This is a string")); will compile and throw an exception at runtime when it calls obj.DoSomething(). The second example CBClass obj(1000, _T("This is a string)); will at the very least throw up an error message in your compiler, at compile time. A good implementation will fail to produce an executable file until you've corrected the error and provided a valid value. VC++ flags a warning but produces an executable if you've set error level to 3 and not checked 'warnings as errors'. I always compile my code at error level 4 and 'warnings as errors'.

The CBClass constructor expects a first parameter of type constsOfInterestToThisClass. This may be either bConstantOfInterestToThisClass1 or bConstantOfInterestToThisClass2 or a variable of type constsOfInterestToThisClass. The compiler will let you define a variable of type constsOfInterestToThisClass but will only let you assign values from the enum values you define. <PRE lang=c++>CBClass::constsOfInterestToThisClass var;
var = CBClass::bConstantOfInterestToThisClass1; // OK
var = 47; // Error

Another issue

From reading the foregoing it's tempting to conclude that the final default: case in CBClass::DoSomething() is superfluous. You might even have thought I left it in by mistake. After all, if you've used an enum correctly the default: should never occur. That's true today. But what if you add a new enum constant sometime down the track and forget to add code to the DoSomething() function to handle it? If your switch statement silently ignores enum values it doesn't know about you run the risk of incurring all kinds of unexpected (and difficult to trace) behaviour. Leaving the default: case in place greatly increases your chances of catching such oversights during program development and testing.

Casts

As one or two readers have pointed out it's possible to defeat the whole point of this article by using casts. For example one could code my error example from above thusly:

and the compiler will happily compile your code. Of course it won't run as you expected but if you left the default: code in the switch statement at least you'll get an exception at runtime and hopefully during program testing. What you're doing here of course is saying to the compiler, in effect, 'you know and I know that 47 isn't a valid constant here but I know better than you do so just go ahead and compile it for me'. Once you've asserted your superior knowledge to the compiler all bets are off.

Interestingly, the compiler considers some casts to be so extreme that it still won't compile them without an intermediate step. Ie, cast something to something else, then cast that something else to the final type.

Conclusion

The compiler will do a lot of error checking for you at compile time, if you let it. Using enum's rather than const's helps the compiler find places in your code where you've made incorrect assumptions. The compiler's a lot more thorough than most of us are when it comes to checking datatypes! <!------------------------------- That's it! --------------------------->

License

Share

About the Author

I've been programming for 35 years - started in machine language on the National Semiconductor SC/MP chip, moved via the 8080 to the Z80 - graduated through HP Rocky Mountain Basic and HPL - then to C and C++ and now C#.

I used (30 or so years ago when I worked for Hewlett Packard) to repair HP Oscilloscopes and Spectrum Analysers - for a while there I was the one repairing DC to daylight SpecAns in the Asia Pacific area.

Afterward I was the fourth team member added to the Australia Post EPOS project at Unisys Australia. We grew to become an A$400 million project. I wrote a few device drivers for the project under Microsoft OS/2 v 1.3 - did hardware qualification and was part of the rollout team dealing directly with the customer.

Born and bred in Melbourne Australia, now living in Scottsdale Arizona USA, became a US Citizen on September 29th, 2006.

I work for a medical insurance broker, learning how to create ASP.NET websites in VB.Net and C#. It's all good.

But on compilation, I get the error, ContextType undeclared identifier.
Also, when I click on the function AddContextItems in the Workspace explorer window, it says, Cannot find defination(Implementation) of this file. Can you tell me why this happens?

Hi ! Great article.
But I have a little question: what happens if this parameter is defined at runtime ? For example it must be provided by reading the value in a configuration file ? Your solution won't work anymore here. I am wrong ?

Most new compilers (e.g. msvc) do not optimise the consts out of the application, for obvious implications in classes etc. They keep the data around just to keep the numbers right, and whereever required substitute the value of the const instead of the referencing the const for the value, thus giving you the speed of an actual const. But you loose space in the binary only to gain the syntactical advantage during development.

String enums would be great but hard to enforce without a lot of compiler support. Remember a string is really a pointer to an array of chars, so the compiler would have to be sure that the pointer being used could only ever point to an array of chars defined in the enum. Aliasing would have to be outlawed if one used a string enum.

On the other hand... one could fake string enums by using a class reference where the strings were private or protected members and the enum 'value' is an integer enum.

where CSomeClass could only be instantiated by instantiating an instance of the stringenum class which in it's turn requires the use of a valid string enum value.

But it's a bit of a workaround ain't it...

I suspect floating point enums are disallowed because of their imprecision. Ie, if a double or float value were specified in the enum as a value with 2 digits to the right of the decimal point, could one allow a value that's identical but for the eighth digit to the right of the decimal point? Ie,

I also found enums very useful. In my coding practice I "recycle" a lot of code by copy/paste. A lot of time, the only difference is the constant. With enums, compiler catches a lot of bugs where I would forget to replace the constants of original code with new constants of different type.

You have an eight-ball and Tommy wants to buy two grams. You bought the eight-ball with a quarter-bag of grass, two reds, a six-pack of Old Milwaukie, and $4 in change. You want a profit margin of 35%. How much hash should you get from Tommy for your blow? - Roger Wright

You have an eight-ball and Tommy wants to buy two grams. You bought the eight-ball with a quarter-bag of grass, two reds, a six-pack of Old Milwaukie, and $4 in change. You want a profit margin of 35%. How much hash should you get from Tommy for your blow? - Roger Wright

hi i am Zakaria khan from Bangladesh. i want to learn visual c++ but i dont know any thing about it. i am also confused because i can't take the decision that from where i should start. Now any one please help me with the most basic code pleaseeeeeeee.

HEllo, Um Mohsin From Pakistan, I want creat a project in C++ but i don't know how i creat Password protection and i want that my title run in random colors.. is it possible or any one can make this for me .. plzzz
BYe

On the whole, I agree with the points of the article, but I think there may be a bit of a potential "gotcha" with enums too, which it's worth bringing to people's attention.

Valid values of an enum are not quite restricted to the values that are explicitly listed; they are in fact restricted to the range of the enum, which holds all the enumerator values rounded up to the nearest larger binary power, minus 1. The example Stroustrup gives is:

enum flag {x = 1, y = 2, z = 4, e = 8}; // range 0:15

If you want to cast an int so that it has the enumerated type "flag", then the cast will succeed for an integer in the range 0 to 15, even though not all of those values have been declared within the enum.

This problem would still occur with enums where the values are implicitly assigned: an enum with nine implicitly assigned members would still have a range of 0 to 15.

Enums are better than a const int, but they're still not proof against the occasional faux pas.