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
There is no way to do this that is inbuilt into the C language AFAIK. If you want to do this you would need to remember the number of members or hard code the number as return value of your function. C can tell you the size in bytes of your structs but not the number of members they contain. Alternatively you could use a member function of your struct to return the hard coded number of members.
C only allows you to determine the number of bytes a structure requires (including padding bytes) using the sizeof
operator. As long as the struct members all have the same type, you can use sizeof(struct foo)/sizeof(membertype)
to compute the number of members. In the general case, with differently sized member types, this is impossible from within the C language (you could post process the source automatically and fill in the result, but that's ugly). C simply does not allow what is called Introspection in other languages (like e.g. perl).
But then, you (and the compiler) know the number of members at compile time. Why do you want to compute a known number at runtime? Maybe you can state the actual problem you are trying to solve and we can point to a solution not involving member counts...
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\n", 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
This cannot be done in C.
If you really need this, you should try a more high level language which supports reflection. (Java, Python ).
http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29