Reputation: 53
What is the difference between
typedef struct complex {
int x;
int y;
};
and
typedef struct complex {
int x;
int y;
} comp;
What does the additional comp
in the second case do?
I have tried defining a new variable of type complex
in the first case and using comp
in the second case, both produced the same result... Please help!
Upvotes: 4
Views: 1082
Reputation: 1248
Long story short :
struct complex {
int x;
int y;
};
// forces you to use :
struct complex c;
But :
typedef struct complex {
int x;
int y;
} comp;
// allows you to use :
comp c;
Typedefs are just a matter of readabilty
Upvotes: 0
Reputation: 2183
struct complex {
int x;
int y;
} comp;
This is the shorthand of creating variable of type complex. comp is present before ; so it is treated as variable of type complex.look ar following code also
struct {
int x;
int y;
} comp;
You can also do this with old compilers that creates a variable of its struct type.
Upvotes: 0
Reputation: 9
The purpose of typedef is to assign a simple name to a type declaration made of one or more type components.
In the first declaration, you do not assign any name to your structure named complex. Therefore the compiler will be generating a warning:
i.e. warning: declaration does not declare anything
Usually, when using typedef with structures [ or unions ], it is preferable (less verbose) to use unnamed structures, as in:
typedef struct {int x; int y;} complex;
Upvotes: 1
Reputation: 122463
The first typedef
is useless, the compile may give you a warning for it.
After the second typedef
, whenever you use struct complex
as a type, you can use comp
instead. You can modify the second code into this equivalent form:
struct complex {
int x;
int y;
};
typedef struct complex comp;
You can see that struct complex
defines a type, while typedef
gives it an alternative name.
Upvotes: 4