D
David Mathog
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,THREE,FOUR};
int main(void){
enum atype test;
(void) fprintf(stdout,"1: %d\n",sizeof(test));
(void) fprintf(stdout,"2: %d\n",sizeof(enum atype));
(void) exit(EXIT_SUCCESS);
}
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_LAST};
int main(void){
enum atype test;
test = I_AM_ALWAYS_LAST ;
(void) fprintf(stdout,"%d\n",test);
(void) exit(EXIT_SUCCESS);
}
Thanks,
David Mathog
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,THREE,FOUR};
int main(void){
enum atype test;
(void) fprintf(stdout,"1: %d\n",sizeof(test));
(void) fprintf(stdout,"2: %d\n",sizeof(enum atype));
(void) exit(EXIT_SUCCESS);
}
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_LAST};
int main(void){
enum atype test;
test = I_AM_ALWAYS_LAST ;
(void) fprintf(stdout,"%d\n",test);
(void) exit(EXIT_SUCCESS);
}
Thanks,
David Mathog