Mircea Ispas
Mircea Ispas

Reputation: 20800

C++ enum used instead of const value

I just read some code similar to next one:

enum 
{
    width = 123,
    height = 321,
    position_x = 234
    position_y = 432
};

...

Widget* w = CreateWidget(position_x, position_y, width, height);

Is there any reason to use enum in this case instead of macros or const values?

EDIT: Is it correct to use enum like this? Is this usage considered some kind of abuse in enum usage?

Upvotes: 1

Views: 151

Answers (4)

n. m. could be an AI
n. m. could be an AI

Reputation: 120079

It may be more convenient to use enum than static const int as a class member.

class A
{
    static const int Foo = 42;
    // may have to define A::Foo somewhere
};

class B
{
    enum { Foo = 42 };
    // done
};

Upvotes: 0

There are plenty of reasons not to use macros. The enum in the question is scoped and won't interfere with the same identifier used in different scopes, so you can for example, defined a member position_x in a class without the macro mangling your class definition.

Comparing the enum to a constant, there are people that prefer the enum as it is guaranteed that it will not add to the binary size of the executable. In the case of a constant, it may add (a bit, well, actually an int) to the size of the binary.

Upvotes: 6

John Dibling
John Dibling

Reputation: 101506

In this particular case, there doesn't appear to be any real deciding factor when choosing between an enum and constant values. Both are better than a macro however, and macros should be avoided in general.

More generally, there are some differentiating aspects between an enum and constants:

  1. enums are distinct types, which is more expressive than integral values
  2. you can take the address of a constant, but you can't take the address of an enum value

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 225212

No, there's no special reason to choose an enum over macros or const int values in this case.

Editorial note: It's certainly legal code to use enum in this fashion, but it is a bit strange looking at first glance.

Upvotes: 3

Related Questions