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
CodePudding user response:
No, not possible. There is no syntax for that.
Tangentially related, what is possible is having anonymous 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.
CodePudding user response:
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.