1

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

  • 4
    Possible duplicate of [C Typedef and Struct Question](http://stackoverflow.com/questions/1110944/c-typedef-and-struct-question) – LPs Dec 05 '16 at 13:29

4 Answers4

5
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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
3

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;
aragaer
  • 17,238
  • 6
  • 47
  • 49
  • Names ending in `_t` are reserved by the standard. You might want to make it just `typedef struct test_s { ... } test_s;`. I don't think there's much value in having the typedefed name different from the struct tag. – Petr Skocik Dec 05 '16 at 13:50
  • Good to know. Will not use `_t` from now on. Difference is just for clarity. – aragaer Dec 05 '16 at 14:17
0

With the first version you can only declare:

test t;

With the second versijon you can choose between:

struct test t;
test t;
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
-3

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;
DMaster
  • 603
  • 1
  • 10
  • 23