CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2000
    Location
    Philadelphia
    Posts
    221

    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?

  2. #2
    Join Date
    Mar 2004
    Posts
    382

    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.

  3. #3
    Join Date
    Feb 2004
    Location
    where Eurasian, Pacific and Philippine tectonic plates meet
    Posts
    229

    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
  •  





Click Here to Expand Forum to Full Width

Featured