C++ typedef and its combination with struct

  • 2020-04-02 02:13:38
  • OfStack


//This is equivalent to creating an alias, or type alias, for an existing type.
//Plastic etc.
typedef int size;

//A character array
char line[81];
char text[81];//=>
typedef char Line[81];
Line text, secondline;

//Pointer to the
typedef char * pstr;
int mystrcmp(pstr p1, pstr p2);//Note: int mystrcmp(const PSTR p1, const PSTR p3) cannot be written; Because const PSTR p1 is interpreted as char * const cp

//Used in combination with structure types
typedef struct tagMyStruct
{
int iNum;
long lLength;
} MyStruct;//(here, MyStruct is the alias of structure type)=>
struct tagMyStruct
{
int iNum;
long lLength;
};//+
typedef struct tagMyStruct MyStruct;

// The structure contains one that points to itself Pointer to the usage 
typedef struct tagNode
{
char *pItem;
pNode pNext;
} *pNode;//=>error
//1)
typedef struct tagNode
{
char *pItem;
struct tagNode *pNext;
} *pNode;
//2)
typedef struct tagNode *pNode;
struct tagNode
{
char *pItem;
pNode pNext;
};
//3) specification
struct tagNode
{
char *pItem;
struct tagNode *pNext;
};
typedef struct tagNode *pNode;

//The difference between "define" and "define"
//1)
typedef char* pStr1;//Recreate the name
#define pStr2 char *//Simple text substitution
pStr1 s1, s2;
pStr2 s3, s4;=>pStr2 s3, *s4; 
//2) if there is an expression in the definition, add parentheses; Typedefs are not needed.
#define f(x) x*x=>#define f(x) ((x)*(x))
main( )
{
int a=6 . b=2 . c ; 
c=f(a) / f(b) ; 
printf("%d \n" . c) ; 
}
//3) typedefs are not simple text substitutions
typedef char * pStr;
char string[4] = "abc";
const char *p1 = string;
const pStr p2 = string;=>error
p1++;
p2++;
//1) the #define macro definition has a special advantage: it can be logically determined using #ifdef,#ifndef, etc., and can be undefined using #undef.
//2) typedefs also have a special advantage: they conform to scope rules, and the scope of a variable type defined with typedefs is limited to the defined function or file (depending on the location of the variable definition), while a macro definition has no such feature.


//
//Structure types are defined in C
typedef struct Student
{
int a;
}Stu;//Declare variable Stu stu1; Or struct Student stu1;
//or
typedef struct
{
int a;
}Stu;//Declare variable Stu stu1;
//Structure types are defined in C++
struct Student
{
int a;
};//Declare the variable Student stu2;

//Distinction is used in C++
struct Student 
{ 
int a; 
}stu1;//Stu1 is a variable. Visit stu1. A
typedef struct Student2 
{ 
int a; 
}stu2;//Stu2 is a structural type that accesses stu2 s2; S2. A = 10;
//Still to be added.


Related articles: