473,554 Members | 4,526 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find the number of elements in an enumerated type?

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>
enum atype {ZERO,ONE,TWO,T HREE,FOUR};
int main(void){
enum atype test;
(void) fprintf(stdout, "1: %d\n",sizeof(te st));
(void) fprintf(stdout, "2: %d\n",sizeof(en um atype));
(void) exit(EXIT_SUCCE SS);
}

One could insert

#define TESTN 5

after the enum statement, and use that, but it still requires the
programmer to count the number of elements, as opposed to having the
computer do it.

Maybe I'm assuming too much. Doesn't the C standard say that the enum
statement, without any "=" within the {}, always assigns the enumerated
values as 0,1,2,3,4? Seems like there should be a way to get the
preprocessor or run time to cough up the number of elements.

I did come up with this method, which will work so long as the special
last element is never displaced from it's position at the end of the
list. It is kind of hideous though:

#include <stdlib.h>
#include <stdio.h>
enum atype {ONE,TWO,THREE, FOUR,FIVE, I_AM_ALWAYS_LAS T};
int main(void){
enum atype test;
test = I_AM_ALWAYS_LAS T ;
(void) fprintf(stdout, "%d\n",test );
(void) exit(EXIT_SUCCE SS);
}
Thanks,

David Mathog
Sep 28 '07 #1
11 5799
David Mathog wrote:
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).
No.

If you must know (which is probably rare), add a known last element.
Even that only works if the values are contiguous and start form 0.

--
Ian Collins.
Sep 28 '07 #2
On Sep 29, 8:33 am, David Mathog <mat...@caltech .eduwrote:
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?
Not directly, but you could declare enums in the following way, using
some preprocessing magic:

#include <stdlib.h>
#include <stdio.h>
#define ENUM_START(type ) enum type {
#define ENUMCONCAT(type ) I_AM_ALWAYS_LAS T_ ## type
#define ENUM_END(type) ENUMCONCAT(type ) };
#define ENUM_SIZE(type) ENUMCONCAT(type )

ENUM_START(atyp e)
ONE,
TWO,
THREE,
FOUR,
FIVE,
ENUM_END(atype)

int main(void)
{
enum atype atest = ENUM_SIZE(atype );
(void) fprintf(stdout, "%d\n",ates t);
(void) exit(EXIT_SUCCE SS);

}

Sep 29 '07 #3
On Sep 29, 2:26 pm, boroph...@gmail .com wrote:
On Sep 29, 8:33 am, David Mathog <mat...@caltech .eduwrote:
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?

Not directly, but you could declare enums in the following way, using
some preprocessing magic:

#include <stdlib.h>
#include <stdio.h>
#define ENUM_START(type ) enum type {
#define ENUMCONCAT(type ) I_AM_ALWAYS_LAS T_ ## type
#define ENUM_END(type) ENUMCONCAT(type ) };
#define ENUM_SIZE(type) ENUMCONCAT(type )

ENUM_START(atyp e)
ONE,
TWO,
THREE,
FOUR,
FIVE,
ENUM_END(atype)

int main(void)
{
enum atype atest = ENUM_SIZE(atype );
(void) fprintf(stdout, "%d\n",ates t);
(void) exit(EXIT_SUCCE SS);
Nice. BUT this way we couldn't assign the value in ENUM.
It's difficult to me.

--coffee

Sep 29 '07 #4
In article <11************ **********@y42g 2000hsy.googleg roups.com>,
<bo*******@gmai l.comwrote:
>#define ENUMCONCAT(type ) I_AM_ALWAYS_LAS T_ ## type
#define ENUM_END(type) ENUMCONCAT(type ) };
#define ENUM_SIZE(type) ENUMCONCAT(type )
I have often used the manual version of this - inserting an extra
item in the enumeration. It has the minor disadvantage that some
compilers (such as gcc) will give a warning about a missing value
in switch statements that cover all the real values.

-- Richard

--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Sep 29 '07 #5
David Mathog wrote:
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>
enum atype {ZERO,ONE,TWO,T HREE,FOUR};
int main(void){
enum atype test;
(void) fprintf(stdout, "1: %d\n",sizeof(te st));
(void) fprintf(stdout, "2: %d\n",sizeof(en um atype));
(void) exit(EXIT_SUCCE SS);
}

One could insert

#define TESTN 5

after the enum statement, and use that, but it still requires the
programmer to count the number of elements, as opposed to having the
computer do it.

Maybe I'm assuming too much. Doesn't the C standard say that the enum
statement, without any "=" within the {}, always assigns the enumerated
values as 0,1,2,3,4? Seems like there should be a way to get the
preprocessor or run time to cough up the number of elements.

I did come up with this method, which will work so long as the special
last element is never displaced from it's position at the end of the
list. It is kind of hideous though:

#include <stdlib.h>
#include <stdio.h>
enum atype {ONE,TWO,THREE, FOUR,FIVE, I_AM_ALWAYS_LAS T};
int main(void){
enum atype test;
test = I_AM_ALWAYS_LAS T ;
(void) fprintf(stdout, "%d\n",test );
(void) exit(EXIT_SUCCE SS);
}
I use your method, David:
enum eModulation {
EM_FM, EM_AM, EM_CM, EM_NUM_MODS};
--
Thad
Sep 29 '07 #6
Richard Tobin wrote:
<bo*******@gmai l.comwrote:
>#define ENUMCONCAT(type ) I_AM_ALWAYS_LAS T_ ## type
#define ENUM_END(type) ENUMCONCAT(type ) };
#define ENUM_SIZE(type) ENUMCONCAT(type )

I have often used the manual version of this - inserting an extra
item in the enumeration. It has the minor disadvantage that some
compilers (such as gcc) will give a warning about a missing value
in switch statements that cover all the real values.
So simply write a suitable switch statement:

switch (enumval) {
case ONE: ...
...
case FOUR: ...
default: fputs("Invalid enumval encountered\n", stderr;
}

or whatever error catching mechanism you prefer.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Sep 29 '07 #7
In article <46************ ***@yahoo.com>,
CBFalconer <cb********@mai neline.netwrote :
>I have often used the manual version of this - inserting an extra
item in the enumeration. It has the minor disadvantage that some
compilers (such as gcc) will give a warning about a missing value
in switch statements that cover all the real values.
>So simply write a suitable switch statement:
>default: fputs("Invalid enumval encountered\n", stderr;
Yes, of course you can do that. But (a) it's annoying to have to do
it in dozens of places, (b) it's putting in code to handle a case that
should never happen, just to shut the compiler up, and (c) it
suppresses the warning when you really have made an error.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Sep 29 '07 #8
Richard Tobin wrote:
CBFalconer <cb********@mai neline.netwrote :
>>I have often used the manual version of this - inserting an extra
item in the enumeration. It has the minor disadvantage that some
compilers (such as gcc) will give a warning about a missing value
in switch statements that cover all the real values.
>So simply write a suitable switch statement:
>default: fputs("Invalid enumval encountered\n", stderr;

Yes, of course you can do that. But (a) it's annoying to have to do
it in dozens of places, (b) it's putting in code to handle a case that
should never happen, just to shut the compiler up, and (c) it
suppresses the warning when you really have made an error.
Please do not strip attributions for material you quote.

No, it's not useless. enum objects can hold any value, they are
not limited to the actually specified set. If one gets into your
system you want to know about it soonest. Without the default the
value is just ignored, which may not be a viable resolution.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Sep 30 '07 #9
On Sep 29, 7:47 pm, *coffee* <coffee....@gma il.comwrote:
On Sep 29, 2:26 pm, boroph...@gmail .com wrote:
On Sep 29, 8:33 am, David Mathog <mat...@caltech .eduwrote:
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?
Not directly, but you could declare enums in the following way, using
some preprocessing magic:
#include <stdlib.h>
#include <stdio.h>
#define ENUM_START(type ) enum type {
#define ENUMCONCAT(type ) I_AM_ALWAYS_LAS T_ ## type
#define ENUM_END(type) ENUMCONCAT(type ) };
#define ENUM_SIZE(type) ENUMCONCAT(type )
ENUM_START(atyp e)
ONE,
TWO,
THREE,
FOUR,
FIVE,
ENUM_END(atype)
int main(void)
{
enum atype atest = ENUM_SIZE(atype );
(void) fprintf(stdout, "%d\n",ates t);
(void) exit(EXIT_SUCCE SS);

Nice. BUT this way we couldn't assign the value in ENUM.
It's difficult to me.

--coffee
Sorry, yes I should have stated that you can only use this if the
constants are contiguous and begin with 0, but I figured this would be
clear from Ian's post.

Regards,
B.

Sep 30 '07 #10

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

Similar topics

1
3021
by: nospam | last post by:
Hi, I have an application whose textareas rows automatically resize onFocus to the number of lines in the textArea. The cols are set to 100% (in a CSS file) in order to always take the full browser width I use textarea.value.split('\n') to find the number of lines. Some lines are longer than the 100% width and they wrap. However, wrappeed...
5
5615
by: Claire | last post by:
Is there an easy way to return the number of elements in an enumerated type please thanks Claire
2
1279
by: Daniel Wilson | last post by:
I have an enumerated type like this: public __value enum MyType{ ABC = 1, DEF = 2, GHI = 3, JKL = 4 }; Later I have a for loop like this: for (ft = MyType::ABC; ft <= MyType::JKL; ft++){
2
5031
by: John Regan | last post by:
Hello All I am trying to find the owner of a file or folder on our network (Windows 2000 Server) using VB.Net and/or API. so I can search for Folders that don't follow our company's specified folder structure and naming conventions and then send a Net send message to those users telling them to rectify. The information I want to get is when...
1
1708
by: davidmcb | last post by:
I have defined an enumerated type that I use in various places in my schema. I am in the process of creating a new complex type that contains an attribute that I want to restrict to NOT being a member of the enumerated type. Is this possible? How? For example: <!-- enumerated type-->
4
4373
by: Shawnk | last post by:
This post is intended to verify that true value semantics DO NOT EXIST for the Enum class (relative to boolean operations). If this is true then (thus and therefore) you can not design state machines in C# where the machine can use the enumerated 'state' to execute (thus the term 'machine' as in 'state machine') the machine operations as...
7
2612
by: John Goche | last post by:
Hello, The following program compiler and runs fine under gcc and produces the output 3. However, I am not sure whether such behavior is legal. In particular, as a related question, how would I go about checking that a supplied integer is contained within the set of values of an enumeration? Is there a way to do this? Thanks,
1
1603
by: senfo | last post by:
I'm using an enumerated type to identify a record type that relates to a unique ID in a database. Identity columns in SQL start at 1, while enumerated types in C# start at 0. I didn't think it would be a big deal because I could just force the values of the enum to start at 1. Database: ID RecordType -- ---------- 1 TypeA
11
7677
by: C C++ C++ | last post by:
Hi all, got this interview question please respond. How can you quickly find the number of elements stored in a a) static array b) dynamic array ? Rgrds MA
0
7506
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...
0
8018
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7872
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6123
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...
1
5423
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...
0
5142
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...
1
2006
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1114
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
823
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.