473,809 Members | 2,819 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Number of elements in an enum

I'm working on a project where I have something like

enum Modes {mode_a, mode_b, ...};

Due to project spec changes, the number of Modes has increased several
times. There are a few places where it's useful to know the number of
image modes (to set the size of bitsets, etc.) Currently I just use a
const int to hold this size:

enum Modes {mode_a, mode_b, mode_c};
const int number_of_modes = 3;

I'm wondering what the style gurus think about this alternative:

enum Modes {mode_a, mode_b, mode_c, mode_sentinel};
const int number_of_modes = mode_sentinel;

The second version requires just a bit less work to maintain, but is it
trying to be too clever? FWIW, the numerical values of the enum
elements are otherwise not used anywhere.
Jan 12 '07 #1
8 32823
Mark P wrote:
I'm working on a project where I have something like

enum Modes {mode_a, mode_b, ...};

Due to project spec changes, the number of Modes has increased several
times. There are a few places where it's useful to know the number of
image modes (to set the size of bitsets, etc.) Currently I just use a
const int to hold this size:

enum Modes {mode_a, mode_b, mode_c};
const int number_of_modes = 3;

I'm wondering what the style gurus think about this alternative:

enum Modes {mode_a, mode_b, mode_c, mode_sentinel};
const int number_of_modes = mode_sentinel;

The second version requires just a bit less work to maintain, but is it
trying to be too clever? FWIW, the numerical values of the enum
elements are otherwise not used anywhere.
An often used way to do this is even:

enum Modes {mode_a, mode_b, mode_c, number_of_modes };

Jan 12 '07 #2
Mark P wrote:
I'm working on a project where I have something like

enum Modes {mode_a, mode_b, ...};

Due to project spec changes, the number of Modes has increased several
times. There are a few places where it's useful to know the number of
image modes (to set the size of bitsets, etc.) Currently I just use a
const int to hold this size:

enum Modes {mode_a, mode_b, mode_c};
const int number_of_modes = 3;

I'm wondering what the style gurus think about this alternative:

enum Modes {mode_a, mode_b, mode_c, mode_sentinel};
const int number_of_modes = mode_sentinel;

The second version requires just a bit less work to maintain, but is it
trying to be too clever? FWIW, the numerical values of the enum
elements are otherwise not used anywhere.
The only problem with that is that the sentinel is a valid enum, so

void SetMode( Modes );

void Foo()
{
SetMode( mode_sentinel ); // Ok, but probably won't work
}

Enums aren't perfect in any case [the compiler needn't complain about
"(Modes)0xfffff " either], but I prefer this style:

enum Modes
{
mode_min = 0,
mode_a = mode_min,
mode_b,
mode_c,
mode_max = mode_c
};
enum { n_modes = (mode_max - mode_min) + 1 };

void Bar()
{
SetMode( n_modes ); // Compile-time error
}

It also allows one to iterate relatively easily:

for( Modes m = mode_min; m <= mode_max; m = Modes(m+1) )
{
// ...
}

Cheers! --M

Jan 12 '07 #3
On Fri, 12 Jan 2007 20:52:59 +0100, Rolf Magnus wrote:

An often used way to do this is even:

enum Modes {mode_a, mode_b, mode_c, number_of_modes };
but does this work when literal values are assigned to the members of the
enumeration, such as when mapping "power of two" bitfields?
Jan 13 '07 #4
On Fri, 12 Jan 2007 19:50:42 +0000, Mark P wrote:
I'm working on a project where I have something like

enum Modes {mode_a, mode_b, ...};

Due to project spec changes, the number of Modes has increased several
times. There are a few places where it's useful to know the number of
image modes (to set the size of bitsets, etc.) Currently I just use a
const int to hold this size:

Just the other day a guy I work with asked me a related question about
whether there is an equivalent in C++ of the Pascal ORD() function to
return the element position of an enumeration member. I don't think there
is, if you assign a non-uniform distribution of literal values to the
members of the enumeration in question. Can someone confirm this?

enum modes { a=12, b=27, c=30, d=900};

How do you determine the (position) of (a)?
Jan 13 '07 #5

noone wrote:
On Fri, 12 Jan 2007 20:52:59 +0100, Rolf Magnus wrote:

An often used way to do this is even:

enum Modes {mode_a, mode_b, mode_c, number_of_modes };

but does this work when literal values are assigned to the members of the
enumeration, such as when mapping "power of two" bitfields?
No. This relies on the default behaviour that the first enumerator has
the numerical value zero and succesive enumerators have their numerical
value increasing by one each time. If you need to assign arbitrary
values to your enumerators, as far as I know there is no way to
programmaticall y determine the total number of enumerators in the enum.

Gavin Deane

Jan 13 '07 #6

noone wrote:
Just the other day a guy I work with asked me a related question about
whether there is an equivalent in C++ of the Pascal ORD() function to
return the element position of an enumeration member. I don't think there
is, if you assign a non-uniform distribution of literal values to the
members of the enumeration in question. Can someone confirm this?

enum modes { a=12, b=27, c=30, d=900};

How do you determine the (position) of (a)?
You can't. But then, what code can you write that depends on the
position of a?

Gavin Deane

Jan 13 '07 #7
On Fri, 12 Jan 2007 16:42:11 -0800, Gavin Deane wrote:
>
noone wrote:
>Just the other day a guy I work with asked me a related question about
whether there is an equivalent in C++ of the Pascal ORD() function to
return the element position of an enumeration member. I don't think
there is, if you assign a non-uniform distribution of literal values to
the members of the enumeration in question. Can someone confirm this?

enum modes { a=12, b=27, c=30, d=900};

How do you determine the (position) of (a)?

You can't. But then, what code can you write that depends on the position
of a?

I tend to agree with you...just wanted more input for the discussion with
my programmer. If you need element position within a predefined set of
values then there are other constructs in the language that can retrieve
that information.

I really think that enums as a feature of C++ are of limited utility and
don't use them often. I think that wrapping the functionality of enum
in a container class adds a lot more flexibility on the long run....yeah,
I know, dereferencing an object member/value is generally a heavier
process than referencing an enum element. :^)

I know that from an early age the comp sci professors beat enumerated
types into our heads, but other than as a (human readable abstraction) I
don't see much utility that can't be emulated by other means...

But I suppose we could degenerate this into an argument over whether
abstract data types are necessary since they all degenerate to list or
array processing in system memory.

Smiles

Jan 13 '07 #8
Gavin Deane wrote:
An often used way to do this is even:

enum Modes {mode_a, mode_b, mode_c, number_of_modes };

but does this work when literal values are assigned to the members of the
enumeration, such as when mapping "power of two" bitfields?

No. This relies on the default behaviour that the first enumerator has
the numerical value zero and succesive enumerators have their numerical
value increasing by one each time. If you need to assign arbitrary
values to your enumerators, as far as I know there is no way to
programmaticall y determine the total number of enumerators in the enum.
In case anyone is interested, I've implemented such a check a while ago
for some project of mine where knowing this was very important. (Actually,
I needed a minor variant of this check, where every enum value had to be
present in some array.)
My check is based on the idea of Duff's device and depends on the compiler
giving a warning if some value of the enum is not handled in a "switch".
It then goes like this:

enum eOption { OPT_FOO, OPT_BAR, OPT_BAZ, OPT_XXX };

static void check_enum(enum eOption opt)
{
int count = 0;
int first = 0;
int i = 0;
switch (opt) {
do {
default:
case OPT_FOO: count += 1;
case OPT_BAR: count += 1;
case OPT_BAZ: count += 1;
case OPT_XXX: count += 1;
if (first == 0)
first = count;
} while (++i < 2);
}
int num = count - first;
printf("This enum has %d entries.\n", num);
}

You have to specify every value of the enum in the switch, but you get
warned by the compiler (use -Wswitch-enum in the case of gcc) if you forgot
one.
I believe this to be safe to use in all circumstances:
- You can reorder the 'case's as you like. (That's why the switch is run
twice.)
- You need not even pass a valid enum value to check_enum().
Any value will do. (The placement of 'default' takes care of that.)

Since enums are static data, you only need to do this check once on program
startup. Of course, if the enum has a lot of entries, you have to do a lot
of typing...

Martin Willers

Jan 17 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
43081
by: Gavin | last post by:
Hi, I'm a newbie to programming of any kind. I have posted this to other groups in a hope to get a response from anyone. Can any one tell me how to make my VB program read the Bios serial number (or would HDD be better, or both?) and put that info into VB prog so the program won't work on another computer. My program uses an MSAccess table. Much appreciated if you can help! Thanks
2
2142
by: Job Lot | last post by:
I have an enumeration as follows Public Enum Delimiters Tab Semicolon Comma Space End Enum How can I return character equivalent of the elements in the enumeration?
5
5628
by: Claire | last post by:
Is there an easy way to return the number of elements in an enumerated type please thanks Claire
2
2325
by: Kimelia | last post by:
For example, I have a public enum: public enum MemberType { MEMBER_NORMAL = 0, MEMBER_VIP = 1, MEMBER_SUPERVIP = 2 } Is it possible to use a foreach (or for) statement to list out all available
1
2209
by: None | last post by:
I'm trying to mark up an enum in a .h file such that when it is emitted to the .idl file the elements of the enum can be marked up with helpstring attributes. Microsoft has a published sample from the ODL help: typedef enum { cows = 1, pigs = 2
14
8662
by: zoltan | last post by:
Hi, Consider a structure as follows : struct dummy { int a; int b; int c; };
2
9214
by: Jay | last post by:
I have a few enums, a shortened example of one is: enum ParamTest {Err, Start, Block, Hold} Is there a programmatic way to find the number of "members" (probably the wrong C# term) of the Enum - this is 4 for the example given. One not very good way that I currently use is to add a dummy "LENGTH" member on the end: enum ParamTest {Err, Start, Block, Hold, LENGTH}
11
5835
by: David Mathog | last post by:
Is there a standard compliant method to access the number of elements in an enumerated type in C, either from within the preprocessor or the running program? The example below compiles and runs but returns 4 twice (the number of bytes used to store a value in test) when the needed answer is 5 (the number of enumerated values in atype). #include <stdlib.h> #include <stdio.h>
3
3147
by: puzzlecracker | last post by:
What's the fastests way to find a number of values in enum. I came up with this. but I think it's over kill. enum Type { VAL1, VAL2, VAL3 }
0
9600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10633
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10375
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9198
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6880
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5548
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5686
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3860
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.