Can I get the size of a struct field w/o creating an instance of the struct?
typedef struct Foo {
typedef BarType int;
BarType bar;
bool baz;
} Foo;
...
sizeof(Foo::BarType)
You can use sizeof of with a pointer to the structure. Consider something like the following:
#include <stdio.h>
typedef struct Foo {
char cbar;
short sbar;
int bar;
bool baz;
long long llbar;
} Foo;
int main (void)
{
struct Foo *p_foo = 0;
printf("Size of cbar: %d\n", sizeof(p_foo->cbar));
printf("Size of sbar: %d\n", sizeof(p_foo->sbar));
printf("Size of bar: %d\n", sizeof(p_foo->bar));
printf("Size of baz: %d\n", sizeof(p_foo->baz));
printf("Size of llbar: %d\n", sizeof(p_foo->llbar));
}
Which gives results such as:
163> size.exe
Size of cbar: 1
Size of sbar: 2
Size of bar: 4
Size of baz: 1
Size of llbar: 8
You can use an expression such as:
sizeof Foo().bar
As the argument of sizeof
isn't evaluated, only its type, no temporary is actually created.
If Foo
wasn't default constructible (unlike your example), you'd have to use a different expression such as one involving a pointer. (Thanks to Mike Seymour)
sizeof ((Foo*)0)->bar