typedef struct

 
################################## 
###   typedef (both C & C++)   ### 
################################## 
 
typedef int foo;   // this declares "foo" as an alias to "int" 
                   // you can use both as below 
int x; 
foo y; 
 
 
########################### 
####   struct (in C)   #### 
########################### 
 
struct S{ 
  int age; 
  char* name; 
}; 
 
===> declares "struct S" data type 
 
NOTE: struct in C can only contain variables, pointers, but not actual functions. struct in C++ is a class thus can contain function definitions. 
 
since only "struct S" namespace is reserved for that custom data type you defined, you can still declare variable "S" 
 
e.g. 
 
struct S foo;    // legal 
S bar;           // illegal, no such namespace as "S" exist 
int S;           // legal, but this is not related to "struct S" at all. 
 
 
now we use typedef on struct. 
 
--------------------- 
 
struct S{ 
  int age; 
  char* name; 
}; 
 
typedef struct S S;   // now aliased "S" to "struct S" so you can use them interchangably. 
typedef struct S K;   // now aliased "K" to "struct S" also 
 
--------------------- 
 
====> the above can be abbreviated as below. 
 
--------------------- 
 
typedef struct S{ 
  int age; 
  char* name; 
} S; 
 
---------------------- 
 
typedef struct S{ 
  int age; 
  char* name; 
} K; 
 
---------------------- 
 
===> now here is another tricky case where you declare an "anonymous" struct and define its alias. 
 
---------------------- 
 
typedef struct{     // notice how you dont write "S" here 
  int age;          // only reserves "S" namespace, not "struct S" 
  char* name;       // so you can only use "S", not "struct S" 
} S;                // but that's perfectly fine. you really only need "S" 
 
---------------------- 
 
 
===> another trick 
 
typedef struct { 
  int X; 
  int Y; 
} Data, *DataPtr;    // see how you reserved not just "Data" but its pointer version too. 
 
// so instead of this line 
  Data* ptr = (Data*) malloc (sizeof(Data)); 
 
// you can use this 
  DataPtr ptr = (DataPtr) malloc (sizeof(Data));   // neat 
 
 
 
 
############################# 
####   struct (in C++)   #### 
############################# 
 
// in C++, struct is the same as class except for the default accessor type. see cpp_class article. 
 
struct S{ 
  int age; 
  char* name; 
}; 
 
====> reserves both "struct S" and "S" namespace already. so no need for typedef. 
 
 
 
(ref) 
http://stackoverflow.com/questions/1675351/typedef-struct-vs-struct-definitions

  1. 2014-07-06 21:22:42 |
  2. Category : unix
  3. Page View:

Google Ads