user2780061
user2780061

Reputation: 343

Typedef/struct declarations

What is the difference between these two declarations, if someone could explain in detail:

typedef struct atom {
  int element;
  struct atom *next;
};

and

typedef struct {
  int element;
  struct atom *next;
} atom;

Upvotes: 24

Views: 47289

Answers (3)

Deep
Deep

Reputation: 11

The general syntax of typedef keyword will be: typedef existing_data_type new_data_type;

typedef struct Record {
    char ename[30];
     int ssn;
    int deptno;
} employee;

Upvotes: 1

Barmar
Barmar

Reputation: 780724

The purpose of typedef is to give a name to a type specification. The syntax is:

typedef <specification> <name>;

After you've done that, you can use <name> much like any of the built-in types of the language to declare variables.

In your first example, you the <specification> is everything starting with struct atom, but there's no <name> after it. So you haven't given a new name to the type specification.

Using a name in a struct declaration is not the same as defining a new type. If you want to use that name, you always have to precede it with the struct keyword. So if you declare:

struct atom {
    ...
};

You can declare new variables with:

struct atom my_atom;

but you can't declare simply

atom my_atom;

For the latter, you have to use typedef.

Note that this is one of the notable differences between C and C++. In C++, declaring a struct or class type does allow you to use it in variable declarations, you don't need a typedef. typedef is still useful in C++ for other complex type constructs, such as function pointers.

You should probably look over some of the questions in the Related sidebar, they explain some other nuances of this subject.

Upvotes: 17

Gangadhar
Gangadhar

Reputation: 10516

This is Normal structure declaration

  struct atom {
      int element;
      struct atom *next;
    };    //just declaration

creation of object

 struct atom object; 

  struct atom {
      int element;
      struct atom *next;
    }object;    //creation of object along with structure declaration

And

This is Type definition of struct atom type

typedef  struct atom {
  int element;
  struct atom *next;
}atom_t;  //creating new type

Here atom_t is alias for struct atom

creation of object

atom_t object;      
struct atom object; //both the ways are allowed and same

Upvotes: 23

Related Questions