Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...