2

When creating a struct you can do

struct name {
 ...
} var1, var2;

to create variables of type struct name.

if you want to do typedef the syntax is

typedef <existing type> <alias> 

to do a typedef for a struct type you do

typedef struct name(optional) {
 ...
} Typename;

where typename is the alias and the struct part is the existing type.

I am wondering if you can combine the above code sections. ex do a typedef on a struct like in the second example and in the same line declare var1 and var2 like we did for the first example. this doesnt seem possible since the Typename seems to take the place of var1 and var2

  • 4
    No you can't combine them. – user3386109 Sep 13 '22 at 04:05
  • 3
    You can either declare variables of the type (`struct name { … } name1, *name2;`) or you can use the `typedef` 'storage class' to specify that the names are aliases for the type(s): `typedef struct name { … } Name, *NamePtr;` (though defining [typedefs for pointers](https://stackoverflow.com/q/750178/15168) should usually be avoided). – Jonathan Leffler Sep 13 '22 at 04:10
  • Note: "optional" is "required" when members of the struct are declared as pointers to the same type of struct (eg: `next` pointers in LLs, `left/right node` pointers in BSTs). – Fe2O3 Sep 13 '22 at 04:49
  • Are you trying to save keyboard? – 0___________ Sep 13 '22 at 05:26

2 Answers2

5

No, not possible. There is no syntax for that.


Tangentially related, what is possible is having untagged struct:

struct {
    ...
} var1, var2;

As a side note, the problem is circumvented by not adding typedefs for structs.


In a more general note, code is easier to understand, if each statement does one thing (like define a variable or define a type). So even if this was possible, doing wouldn't necessarily be a good idea.

By this same principle, if you should decide to follow it, you should write:

struct name {
 ...
};

struct name var1, var2;

or, with typedef:

typedef struct name {
 ...
} name;

name var1, var2;

Note: if you don't need a pointer to same struct type in the struct itself (needed for linked lists and trees, basically), you can use untagged struct: typedef struct { ... } name;

hyde
  • 60,639
  • 21
  • 115
  • 176
2

You cannot do that because typedef is synthetically an "storage-class specifier" like static, extern, auto, register and _Threadlocal. As result it is not possible to have no storage qualifier (default one) and typedef at the same time. However, one can do achieve the desired effect by placing typedef below definition of var1 and var2 object.

struct name {
 ...
} var1, var2;

typedef struct name Typename;

The upcoming C23 standard will support typeof which would let one create aliases for untagged structs.

struct  {
 ...
} var1, var2;

typedef typeof(var1) Typename;

The typeof is already supported by many compilers (gcc, clang, icc) with an exception of infamous MSVC.

tstanisl
  • 13,520
  • 2
  • 25
  • 40