Reputation: 51
Can anyone explain me what is the difference between this:
typedef struct{
char a[10];
int b;
char c[8];
...
}test;
and this:
typedef struct test{
char a[10];
int b;
char c[8];
...
}test;
Thanks
Upvotes: 1
Views: 120
Reputation: 17858
Having "test" in two different places is a bit confusing. I usually write code like this:
typedef struct test_s {
...
} test;
Now I can either use type struct test_s
or just test
. While test
alone is usually enough (and you don't need test_s
in this case), you can't forward-declare pointer to it:
// test *pointer; // this won't work
struct test_s *pointer; // works fine
typedef struct test_s {
...
} test;
Upvotes: 3
Reputation: 170279
typedef struct{
char a[10];
int b;
char c[8];
...
}test;
The above defines an anonymous struct and immediately typedef
s it to the type alias test
.
typedef struct test{
char a[10];
int b;
char c[8];
...
}test;
This however, creates a struct named struct test
as well as adding a typedef
for it.
In the first case, you will not be able to forward declare the struct
if you need to.
There's also a philosophy (which I happen to agree with to a point), that typedef
ing all structures by default makes code less readable, and should be avoided.
Upvotes: 5
Reputation: 641
Short answer: They're the same (in your code)
Long answer: Why put test
between typedef struct
and {
? Is that pointless?
This (struct name test
) is pointless in your code
In this code however, it's not:
struct Node {
int data;
struct Node * next;
} head;
Upvotes: -3
Reputation: 9763
With the first version you can only declare:
test t;
With the second versijon you can choose between:
struct test t;
test t;
Upvotes: 0