-
July 7th, 2005, 09:56 PM
#1
sizeof(enum) ???
Hello gurus,
I know this question doesn't really belong to VC++ section, but here goes anyway....
I'd like to automatically detect how many elements my 'enum' data structure contains, something like
Code:
enum ENUM1 { A = -4, B, C, D, E };
printf("%d\n", MagicFunctionThatReturnsNumOfElementsInENUM1() );
??? sizeof(ENUM1) always returns 4
I guess I could write
Code:
int MagicFunctionThatReturnsNumOfElementsInENUM1()
{
return (E-A+1);
}
but then I gotta know the names of the first and last element of the enum...
Furthermore, this wouldn't work with enums like this
Code:
enum ENUM1 { A, B, C=56, D, E };
Any ideas? Is it even doable?
-
July 7th, 2005, 10:44 PM
#2
Re: sizeof(enum) ???
The easiest way for me whenever I need such a functionality is, the following.
Code:
enum DATA {
A = 0,
B,
C,
D,
E,
Total
}
This way Total will have the total number of elements, excluding Total itself. So to get the size, do the following
Code:
DATA Data;
int totalElements = Data.Total;
Just make sure you intial value is 0.
With the function you had in mind and even with my recommendation be carful with the following
Code:
int MagicFunctionThatReturnsNumOfElementsInENUM1()
{
return (E-A+1);
}
Just make sure you don't have the following type of enumeration, or else your function will give you the incorrect results
Code:
enum ENUM1 {
A = -4,
B,
C,
D = 1000000,
E };
Your function would return 1000001 - (-4) + 1 = 1000006, which is of course incorrect.
-
July 8th, 2005, 12:17 AM
#3
Re: sizeof(enum) ???
From your code it is not possible imo, however if you don't mind calling a C program, or a simple Perl script...
Code:
open F, "enum.h" or die "couldnt open";
while (<F>) { print scalar (tr/,//)+1 if (/\benum\b/); }
works only with enum on a line by itself, with no 'enum'or ',' comment...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|