devoured elysium
devoured elysium

Reputation: 105067

What is the difference between declaring and defining a structure?

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;
};

Upvotes: 6

Views: 1510

Answers (5)

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

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.

Upvotes: 18

Chris Lutz
Chris Lutz

Reputation: 75399

The two do different things:

struct {
   char a;
   int b;
} x;

Declares a variable x of type struct { char a; int b; }

struct x {
   char a;
   int b;
};

Declares a type struct x. To get a variable of that type, you would later need to do this:

struct x x = {0};
x x = {0}; // C++ only

The second one is more common, because it can make declarations shorter, especially if you have to change your struct. The first is used if you're never going to need the structure again and don't want to pollute your namespace. So basically never.

Upvotes: 2

jesup
jesup

Reputation: 6984

The first defines an variable named 'x' whose type is an unnamed structure.

The second defines a structure named x, but doesn't define anything that uses it.

Upvotes: 4

peterchen
peterchen

Reputation: 41096

The first is equivalent to

struct unnamed_struct {  char a;    int b;};
unnamed_struct x;

only that the struct type has no name.

Upvotes: 2

Fabio Vinicius Binder
Fabio Vinicius Binder

Reputation: 13214

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;

Upvotes: 4

Related Questions