2

What are bar and x below and why are they located there? Are they instances of the structs?

I was reading this Stackoverflow question whose code I have pasted here and I found that the poster and one of the answers use variable names [bar and x] after the definition of the struct. cpp reference doesn't use this syntax their examples and I don't know what the syntax is called nor what the syntax does to look it up.

If it is just about creating an instance of a struct, why not write it in the next line like cpp reference does in its examples?

struct _bar_ 
    {
        int a;
    } bar; 
struct test {
      int value;
   } x;
heretoinfinity
  • 1,308
  • 3
  • 11
  • 29

3 Answers3

3

struct test { int value; } x; declares x to be an object of type struct test. It is a simple declaration, the same as int x, with struct test { int value; } in place of int.

Eric Postpischil
  • 168,892
  • 12
  • 149
  • 276
  • 1
    why do it that way though? Isn't it hard to see the `bar`? Why not write it on a new line? Is this a one-off thing? – heretoinfinity Feb 09 '20 at 16:37
  • 2
    If by “one-off” thing, you are asking whether `struct test` can be used again later in the same scope to declare additional objects, then, no, it is not a one-off thing; it may be used again as `struct test` or (in C++ but not C) `test`. If the tag were omitted, the structure would be a unique definition of a type without a name. As for “why”, people learn to read code. Additionally, the identifiers for the declared objects do appear on a new line, as `} bar;` and `} x;` appear on lines of their own. This becomes quite recognizable after a little experience. – Eric Postpischil Feb 09 '20 at 16:43
1

In

struct _bar_ {
    int a;
} bar; 

bar is a declaration of a variable of type struct _bar_.

It's the same as:

struct _bar_ bar;
anastaciu
  • 22,293
  • 7
  • 26
  • 44
  • why do it that way though? Isn't it hard to see the `bar`? Why not write it on a new line? Is this a one-off thing? – heretoinfinity Feb 09 '20 at 16:37
  • I guess it's a matter of style, both are the same, you can use the created variable `bar` in the same way for both declaration cases. – anastaciu Feb 09 '20 at 16:52
1

By using this definition:

struct _bar_ 
    {
        int a;
    } bar; 

Here you've just declared a variable of type struct _bar_.

struct product {
  int weight;
  double price;
} ;

product apple;
product banana, melon;

In this case, where object_names are specified, the type name (product) becomes optional: struct requires either a type_name or at least one name in object_names, but not necessarily both.

From: Data structures

some user
  • 1,643
  • 2
  • 12
  • 28