struct

Hi all,

what is the difference between
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct my_struct
{
   int one;
   int two;
};

and

typedef struct
{
  int one;
  int two;
} my_struct;



many thanks,

http://en.wikipedia.org/wiki/Typedef
alot there about typedef.
The second way is often used in C. I don't know the details but if you did the first one in C you would have to write struct my_struct in a lot of places instead of just my_struct. Example: To define a variable named foo of type my_struct you would have to write struct my_struct foo; instead of just my_struct foo;

In C++ there is no need to use the typedef version because you can always use my_struct without struct in front.
Yeah, basically what Peter87 said. The latter method is C code and isn't really used as much in C++. The former is generally preferred.
There are many details that you should take into account. I will show at least two of them.
For example in the first definition the name of the structure is visible inside its definition and you can refer to it.

1
2
3
4
5
6
struct my_struct
{
   int one;
   int two;
   my_struct *next;
};


In the second declaration you can not do so because the typedef name is not visible inside the definition of the structure.

1
2
3
4
5
6
typedef struct
{
   int one;
   int two;
   my_struct *next;   // compilation error  
} my_struct;


Another example. You can redeclare a name of a structure but you can not redeclare a typedef name with another type.

1
2
3
4
5
6
7
8
9
struct my_struct
{
   int one;
   int two;
};

int my_struct;

struct my_struct str;


1
2
3
4
5
6
7
8
9
typedef struct
{
   int one;
   int two;
} my_struct;

int my_struct; // compilation error

my_struct str; // compilation error 

Last edited on
Topic archived. No new replies allowed.