typedef or not?

Started by
16 comments, last by rozz666 16 years, 8 months ago
Why do many people use: typedef struct {...) name; instead of simply: struct name {...}; ?
Advertisement
because they're writing C code rather than C++.
Its a C-ism, in C you cannot instantiate a struct type without using the struct keyword, the following is dis-allowed: name my_object;
Instead the instantiation should read: struct name my_object;
But if you use a typedef then you can ditch the struct keyword.

In C++ however this is a non-issue, you dont need to use the struct or class keywords to instantiate either of them.

So whether to use typedef in this way or not depends on the language you're using.
I c, thx :)
Typedefs do still come in handy for C++, especially for template classes.
typedef struct name { //stuff } anothername;

same as:
struct name { //stuff };typedef anothername name;
?


typedef struct name { //stuff } name;

same as:
struct name { //stuff };typedef name name; //prolly impossible, so totally useless
?

I'm confused :D
Quote:Original post by GreyHound
I'm confused :D


In both C and C++, struct something {} defines a structure named something, and that name becomes usable immediately. In both C and C++, typedef type name; associates name as an alias for the described type.

The difference is that in C++, structure names and typedef alias names exist within the same namespace (in the C sense, not the C++ sense) while in C there is a specific structure namespace independent from the namespace used by typedef aliases, functions and variables. One specifies the namespace by using the struct keyword before the name (so name would be looked for in the alias/function/variable namespace, while struct name would be looked for in the structure namespace).
typedef struct name_s {} name_t;


is the same as (in C):

struct name_s { };typedef struct name_s name_t;


or the same as (in C++):

struct name_s { };typedef name_s name_t;


and practically the same as (in C++):

struct name_t { };
Quote:Original post by rozz666
and practically the same as (in C++):

I would not us the phrase 'practically the same' unless you mean 'quite different.'

For example.
  typedef struct S {    int i;  } T1;  class T2 {    int i;  };  void f1(S p)  {  }  void f2(T2 p)  {  }  void f3(T1 p)  // error: already defined  {  }  int main()  {    S s;    T1 t1 = s; // okay, the same type    T2 t2 = s;  // error: unrelated types.  }

Stephen M. Webb
Professional Free Software Developer

  typedef struct S {    int i;  } T1;  class T2 {    int i;  };  <removed>  void f3(T1 p)  // error: already defined  {  }  <removed>


I don't get an error for this in Visual C++ 2005 Express.

This topic is closed to new replies.

Advertisement