Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a common C/C++ macro to determine the size of a structure member?

Tags:

c++

sizeof

In C/C++, how do I determine the size of the member variable to a structure without needing to define a dummy variable of that structure type? Here's an example of how to do it wrong, but shows the intent:

typedef struct myStruct {
  int x[10];
  int y;
} myStruct_t;

const size_t sizeof_MyStruct_x = sizeof(myStruct_t.x);  // error

For reference, this should be how to find the size of 'x' if you first define a dummy variable:

myStruct_t dummyStructVar;

const size_t sizeof_MyStruct_x = sizeof(dummyStructVar.x);

However, I'm hoping to avoid having to create a dummy variable just to get the size of 'x'. I think there's a clever way to recast 0 as a myStruct_t to help find the size of member variable 'x', but it's been long enough that I've forgotten the details, and can't seem to get a good Google search on this. Do you know?

Thanks!

like image 977
Matt Ball Avatar asked Nov 27 '22 01:11

Matt Ball


2 Answers

In C++ (which is what the tags say), your "dummy variable" code can be replaced with:

sizeof myStruct_t().x;

No myStruct_t object will be created: the compiler only works out the static type of sizeof's operand, it doesn't execute the expression.

This works in C, and in C++ is better because it also works for classes without an accessible no-args constructor:

sizeof ((myStruct_t *)0)->x
like image 146
Steve Jessop Avatar answered Dec 19 '22 16:12

Steve Jessop


I'm using following macro:

#include <iostream>
#define DIM_FIELD(struct_type, field) (sizeof( ((struct_type*)0)->field ))
int main()
{
    struct ABC
    {
        int a;
        char b;
        double c;
    };
    std::cout << "ABC::a=" << DIM_FIELD(ABC, a) 
              << " ABC::c=" << DIM_FIELD(ABC, c) << std::endl;

    return 0;
}

Trick is treating 0 as pointer to your struct. This is resolved at compile time so it safe.

like image 23
Dewfy Avatar answered Dec 19 '22 17:12

Dewfy