Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

c - How do I get the number of members in a structure?

I want to count the number of members in a structure. For example:

typedef struct
{
    char    MrChar;
    int MrInt;
    long    MrLong;
} Bg_Typedef;
Bg_Typedef FooStr;

I create a function prototype that should return number of members in the structure

int NumberOfMem(Bg_Typedef *psStructure); 

=> NumberOfMem(&FooStr) should return 3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It can be done with X_MACRO's.

Do something like this:

#define X_BG_MEMBERS 
    X(char, MrChar) 
    X(int, MrInt) 
    X(long, MrLong)

typedef struct {
#define X(type, member) type member;
    X_BG_MEMBERS
#undef X
} Bg_Typedef;

Bg_Typedef FooStr;

Define a function which will count the members. Can also just be a variable, but make the variable static const so that it is not overwritten

static int
bg_members_count() {
    #define X(_, __) +1
    static int COUNT = 0
    X_BG_MEMBERS;
    #undef X
    
    return COUNT;
}

Now you can do something like this in main:

#include <stdio.h>
...

int main() {
    printf("The number of members defined in Bg_Typedef is %d
", bg_members_count());
}

You should get something like:

The number of members defined in Bg_Typedef is 3

You might also just want a constant, so you can do the following

#define X(_, __) +1
static const int COUNT = X_BG_MEMBERS;
#undef X

Alternative Pattern

In order to avoid having lots of #define X... followed by #undef X, it may be beneficial to do something like this instead:

#define X_BG_MEMBERS(X) 
    X(char, MrChar) 
    X(int, MrInt) 
    X(long, MrLong)

#define BG_STRUCT_FIELD(type, field) type field;
#define BG_COUNT_MEMBER(_, __) +1

typedef struct {
  X_BG_MEMBERS(BG_STRUCT_FIELD)
} Bg_Typedefarguably;

static int
bg_members_count() {
    static int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);    
    return COUNT;
}

// OR constant
// static const int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);

It works the same as the above, but should be noticeably more readable. See ref.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...