Reputation: 107
I have a bit of confusion between the below declarations - could you please help clear it up?
typedef struct {
int a;
int b;
} example;
And this
struct something {
int a;
int b;
} ob;
And I am not sure what the below would even mean?
typedef struct foo {
int a;
int b;
} bar;
Upvotes: 2
Views: 74
Reputation: 409482
With
typedef struct {
int a;
int b;
} example;
you define an unnamed structure, but define a type-alias example
for the structure. That means you can only create instance of the structures using the example
"type", like e.g.
example my_example_structure;
With
struct something {
int a;
int b;
} ob;
you define a structure named something
, and an instance (a variable) of that structure named ob
. You can use struct something
to create new variables of the structure:
struct something my_second_ob;
The variable ob
can be used like any other instance of the structure:
printf("b = %d\n", ob.b);
Lastly, with
typedef struct foo {
int a;
int b;
} bar;
you define a structure named foo
, so you can use e.g. struct foo
to define variables. You also define a type-alias bar
which can also be used. Like for example
struct foo my_first_foo;
bar my_second_foo;
The general syntax for typedef
is
typedef <actual type> <alias name>;
In the last case of your examples, the <actual type>
is
struct foo {
int a;
int b;
}
and the <alias name
is bar
.
Upvotes: 4
Reputation: 171177
typedef struct {
int a;
int b;
} example;
This one defines an unnamed structure type and introduces example
as a type alias for that structure type. You can therefore refer to that structure type only as `example.
struct something {
int a;
int b;
} ob;
This one defines a structure type something
and also declares an object ob
of that type. You can refer to the structure type only as struct something
.
typedef struct foo {
int a;
int b;
} bar;
This one defines a structure type named foo
and introduces bar
as a type alias for that structure type. You can refer to that structure type as struct foo
or as bar
.
Upvotes: 5