Carlo Di Dato
Carlo Di Dato

Reputation: 51

typedef struct clarification

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

Answers (4)

aragaer
aragaer

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

typedef struct{
 char a[10];
 int b;
 char c[8];
 ...
}test;

The above defines an anonymous struct and immediately typedefs 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 typedefing all structures by default makes code less readable, and should be avoided.

Upvotes: 5

DMaster
DMaster

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

Serve Laurijssen
Serve Laurijssen

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

Related Questions