Is there a practical difference between:
typedef struct
{
float x;
float y;
} Point;
Point origin = {0.0, 0.0};
struct Point
{
float x;
float y;
}
struct Point origin = {0.0, 0.0};
Are both of these correct?
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.
Sign up to join this communityIs there a practical difference between:
typedef struct
{
float x;
float y;
} Point;
Point origin = {0.0, 0.0};
struct Point
{
float x;
float y;
}
struct Point origin = {0.0, 0.0};
Are both of these correct?
Yes. The first version
typedef struct
{
// members
} Point;
defines an anonymous struct (i.e., a struct that doesn't have a name) and gives it a type name (i.e., Point
). Unfortunately, if you decide to have a pointer to a recursive member inside your struct this way, you won't be able to do that because as long as you're before the semicolon that ends the typedef
statement, you won't be able to use the type name Point
.
On the other hand,
typedef struct Point
{
// members
} Point;
defines a struct named struct Point
and gives it a type name Point
. Both struct Point
and Point
can be used interchangeably. You'll also be able to create a recursive member inside your struct as follows
struct Point *pp;
Hope that helps!
struct
variable fields explicitly:origin.x = 0.0;
andorigin.y = 0.0;
– user2477 Nov 14 '14 at 8:04