struct {
char a;
int b;
} x;
Why would one define a struct like that instead of just declaring it as:
struct x {
char a;
int b;
};
Declaration means that variable is only declared and memory is allocated, but no value is set. However, definition means the variables has been initialized.
For a variable, declaration means just stating its data type along with giving it name for memory allocation; while definition means giving the value of that variable.
A structure can be defined as a single entity holding variables of different data types that are logically related to each other. All the data members inside a structure are accessible to the functions defined outside the structure.
For the difference between definition and declaration, one should consider their literal meaning first which includes Declare means to announce or proclaim while Define means to describe some entity.
In the first case, only variable x
can be of that type -- strictly, if you defined another structure y
with the same body, it would be a different type. So you use it when you won't ever need any other variables of the same type. Note that you cannot cast things to that type, declare or define functions with prototypes that use that type, or even dynamically allocate variables of that type - there is no name for the type to use.
In the second case, you do not define a variable - you just define a type struct x
, which can then be used to create as many variables as you need of that type. This is the more normal case, of course. It is often combined with, or associated with, a typedef
:
typedef struct x
{
char a;
int b;
} x;
Usually, you'd use a more informative tag name and type name. It is perfectly legal and safe to use the same name for the structure tag (the first 'x') and the typedef name (the second 'x').
To a first approximation, C++ automatically 'creates a typedef' for you when you use the plain 'struct x { ... };' notation (whether or not you define variables at the same time). For fairly complete details on the caveats associated with the term 'first approximation', see the extensive comments below. Thanks to all the commentators who helped clarify this to me.
In the first case you are declaring a variable. In the second, a type. I think a better approach would be:
typedef struct tag_x {
char a;
int b;
} x;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With