C/C++: size of a typedef struct containing an int and enum == sizeof(int)?
c, c++, enumeration, size, struct
Solution
You are not declaring anything with:
enum {token=0x123456};
Your declaration is similar to:
typedef struct {
int size;
int;
} Message;
If you declare your struct like this:
typedef struct {
int size;
enum {token=0x123456} e;
} Message;
There will be two fields, but `e` will not be initialized to anything. You need to set it manually for every instance: `message.e=token`.
The correct way to achieve what you want is, to use constructors in C++:
struct Message {
int size;
int token;
Message() : token(0x123456) {};
};
Or non-static data member initializers in C++11:
struct Message {
int size;
int token=0x123456;
};
There is no way to initialize field in struct declaration in C.
Problem
I am using gcc version 4.3.3 on my Ubuntu (i686). I have written a stripped down test program to describe my lack of understanding and my problem. The program shall tell me the size of the struct, which I implemented. So I have a typedef struct for a Message and a little main to play around: ``` #include <stdio.h> typedef struct { int size; enum {token=0x123456}; } Message; int main(int argc, char * argv[]) { Message m; m.size = 30; printf("sizeof(int): %d\n",sizeof(int)); printf("sizeof(0x123456): %d\n",sizeof(0x123456)); printf("sizeof(Message): %d\n",sizeof(Message)); printf("sizeof(m): %d\n",sizeof(m)); } ``` While compiling this source with gcc I get the following warning, which I don't understand: ``` $ gcc sizeof.c sizeof.c:5: warning: declaration does not declare anything ``` Line 5 refers to the enum line. I want that token in every Message, that I create. What am I doing wrong? What do I have to change to get rid of that warning? My main contains several calls of sizeof(). When I run the program, you can see in the output that the integer has the size of four, the hex number has the size of 4, but the typedef struct Message has the size of 4, too: ``` $ ./a.out sizeof(int): 4 sizeof(0x123456): 4 sizeof(Message): 4 sizeof(m): 4 ``` That is very confusing to me. Why has Message the size of 4, although it contains an integer and an integer within an enum, each with the size of 4. If the sizeof(Message) would be at least 8, it would be logical to me. But why is it only 4? How do I get the real size in Bytes of my Message? Or is this really the real size? If so, why? Is there a difference in getting the size of a Message between C and C++?