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;
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With