typedef summary (from Wikipedia)

Source: Internet
Author: User
Tags define definition

Usage Summary edit How do you create a platform-independent data type that hides clumsy and incomprehensible syntax? use typedef to create synonymous words for existing types, define easy-to-remember type names
1 typedef int size;
12345678910 void measure(size*psz);size array[4];  size len=file.getlength();std::vector<size>vs;
typedef can also disguise composite types, such as pointers and arrays. For example, you do not have to repeat an array of 81-character elements as follows:
123 char line[81];char text[81];
Simply defined, the line type represents an array of characters with 81 elements, using the following method:
12345 typedefchar Line[81]; Line text,line;getline(text);
Similarly, you can hide the pointer syntax as follows:
1 typedef char* pstr;
1 int mystrcmp(const pstr p1,const pstr p3);
With the GNU GCC and g++ compilers, there is a warning, in order that ' const PSTR ' is interpreted as ' char* const ' (a pointer constant pointing to char), whereas in fact, the const char* and char* Const does not express the same meaning (see C + + Primer version fourth P112). char * Const CP: Defines a pointer constant that points to a character, a const pointer, and a constant pointer. Const char* P: Defines a pointer to a character constant, which is a constant pointer. Char const* p: equals the const char* p. In order to obtain the correct type, it should be stated as follows:
1 typedef const char* pstr;
2 Linguistic usage editing Basic explanationA typedef is a C-language keyword that defines a new name for a data type. The data types here include the internal data type (INT,CHAR, etc.) and the custom data type (struct, etc.). The purpose of using TypeDef in programming is generally two, one is to give the variable a new name that is easy to remember and meaning, and the other is to simplify some more complex type declarations. As to what is so subtle about typedef, you should continue to look at the specific aspects of the problem. 2. typedef & STRUCTURE Problems When you define a structure with the following code, the compiler reports an error, why? is C language not allowed to include pointers to its own in the structure? Please guess first, then read the following explanation:
12345678 typedef struct tagNode{char* pItem; pNode pNext;}*pNode;
Analysis: 1, the most simple use of typedef
1 typedef long byte_4;
Give the known data type long a new name, called Byte_4. 2, typedef and structure in combination with the use
12345678910 typedef struct tagMyStruct{int iNum; long lLength;}MyStruct;
This statement actually completes two operations: 1) Define a new structure type
12345678910 struct Tagmystruct  {   int INum;   long Llength;  
Analysis: Tagmystruct called "tag", or "tag", is actually a temporary name, the struct keyword and tagmystruct together, constitute this structure type, regardless of whether there is a TypeDef, this structure exists. We can use struct tagmystruct varname to define variables, but it is important to note that it is wrong to use tagmystruct varname to define variables, because structs and tagmystruct together can represent a struct type. 2) typedef has a name for this new structure, called MyStruct. typedef struct TAGMYSTRUCT mystruct; therefore, MyStruct is actually equivalent to a struct tagmystruct, and we can use MyStruct varname to define variables. The answer and analysis of the C language is of course allowed to include pointers to its own structure, and we can see countless examples of the implementation of data structures such as linked lists, the fundamental problem with this code is the application of typedef. According to our above description can know: The process of building a new structure encountered the Pnext domain declaration, the type is pnode, to know that Pnode represents the type of the new name, then the type itself has not been established, the type of the new name also does not exist, That means the compiler doesn't know Pnode at all. There are several ways to solve this problem: 1),
12345678910 typedef struct tagNode{char* pItem;  struct tagNode* pNext;}*pNode;
2),
12345678910 typedef struct tagNode* pNode;struct tagNode{ char* pItem;pNode pNext;};
Note: In this example, you use a typedef to give a new name to a type that is not yet fully declared. The C language compiler supports this practice. 3), Standard practice:
123456789 struct tagNode{char* pItem; struct tagNode* pNext;};typedef struct tagNode* pNode;
3. typedef & #define的问题有下面两种定义pStr数据类型的方法, what's the difference between the two? Which is a little better?
123 typedef char* pStr;#define pStr char*
Answer and analysis: Generally speaking, typedef is better than # define, especially in the case of pointers. Take a look at the example:
1234567 typedef char* pStr1;#define pStr2 char*  pStr1 s1,s2;pStr2 s3,s4;
In the variable definition above, S1, S2, S3 are defined as char *, and S4 is defined as char, not the pointer variable we expect, the root cause is that # define is simply a string substitution and a typedef is a new name for a type. In the above example, define statement must be written pStr2 S3, *s4; This can be done normally. #define用法例子:
1234567 #definef(x)x*xmain(){inta=6,b=2,c;c=f(a)/f(b);printf("%d\n",c);}
The output of the following program is: 36. For this reason, when you refer to using the # define definition in many C programming specifications, if the definition contains an expression and you must use parentheses, the definition above should be defined as follows:
1 #definef(x)((x)*(x))
Of course, if you use typedef there is no such problem. 4. typedef & #define的另一例下面的代码中编译器会报一个错误, do you know which statement is wrong?
123456 < Code class= "CPP keyword bold" >typedef  char   *PSTR; char  string[4]= "abc" const  char   *p1=string; const  pstrp2=string; p1++; p2++;
Answer and Analysis: It is p2++ error. This question reminds us again: TypeDef and # define are different, it is not a simple text substitution. The const PSTR P2 in the above code is not equal to the const char * p2. Const PSTR P2 and const long x are essentially no different, they are read-only restrictions on variables, except that the data type of the variable p2 is defined by ourselves rather than by the intrinsic type of the system. Therefore, the meaning of const PSTR P2 is that the variable P2 with the qualification data type char * is read-only and therefore p2++ error. #define与typedef引申谈1) #define宏定义有一个特别的长处: You can use the #ifdef, #ifndef等来进行逻辑判断, and you can use #undef to cancel the definition. 2) typedef also has a special advantage: it conforms to the scope rule, the variable type defined by typedef is scoped to the defined function or file (depending on where the variable is defined), and the macro definition does not have this attribute. 5. typedef & Complex variable declarations in programming practice, especially when looking at other people's code, often encounter more complex variable declarations, using TypeDef to simplify their own value, such as: The following is a declaration of three variables, I want to use typdef to define an alias for them, What should I do? >1:int * (*a[5]) (int, char*), >2:void (*b[10]) (void (*) ()); >3. Doube (*) (*PA) [9]; the answer and analysis: The method of establishing a type alias for a complex variable is simple, you simply replace the variable name with the type name in the traditional variable declaration expression, and then add the keyword typedef to the beginning of the statement. >1:int * (*a[5]) (int, char*);//pfun is a type alias that we built typedef int * (*PFUN) (int, char*);//Use a new type of definition to declare an object, equivalent to int* (*a[5]) (int , char*);p fun a[5];>2:void (*b[10]) (void (*) ());//First declare a new type typedef void (*pfunparam) for the blue portion of the above expression;// The whole declares a new type typedef void (*pfun) (pfunparam);//Use a new defined type to declare an object, equivalent to void (*b[10]) (void (*) ());p fun b[10];>3. Double (*) () [1]  (*PA) [9][2] ;//first declares a new type typedef double (*pfun) for the blue portion of the above expression,//whole declares a new type typedef pfun (* Pfunparam) [9];//uses a new type of definition to declare an object, equivalent to a double (*) () (*PA) [9];p Funparam PA;PA is a pointer to an array with 9 elements, each of which is "Doube (*) () "--also a pointer to a function, the function argument is null, and the return value is" double ".3 code simplified edit The typedef behavior discussed above is somewhat like a #define macro, substituting its actual type for synonymous words. The difference is that the TypeDef is interpreted at compile time, so the compiler is able to cope with the text substitution beyond the preprocessor's capabilities. For example: TypeDef int (*PF) (const char *, const char *); This declaration introduces the PF type as a synonym for the function pointer, which has two const char * type parameters and a return value of type int. If you want to use the following form of a function declaration, then this typedef is indispensable: PF Register (pf pf); The parameter of register () is a PF-type callback function that returns the address of a function whose signature is the same as the name previously registered. Take a deep breath. Let me show you how we implemented this declaration without a typedef: INT (*register (int (*PF) (const char *, const char *))) (const char *, const char *); few programs To understand what it means, not to mention the risk of error caused by this convoluted code. Obviously, using a typedef here is not a privilege, but a necessity. Skeptics may ask, "OK, does anyone else write such a code?" , a quick look at the header file revealing the signal () function, a function with the same interface. typedef and Storage class keywords (storage class specifier) This is not a bit surprising, typedef like auto,extern,mutable,static, and register, is a storage class keyword. This is not to say that typedef really affects the storage characteristics of an object; it simply says that in the statement composition, the typedef declares a variable declaration that looks like a static,extern type. The following will take you to the second trap: typedef register INT Fast_counter; Error compiling pass. The problem is that you cannot have more than one storage class keyword in a declaration. Because the symbol typedef already occupies the location of the storage class keyword, the register (or any other storage class keyword) cannot be used in a typedef declaration.4 Platform Development editor typedef has another important purpose, which is to define machine-independent types, for example, you can define a floating-point type called REAL, which can achieve the highest precision on the target machine: typedef long double REAL; on a machine that does not support long double, The typedef looks like this: typedef double real; and, on machines that are not even double-supported, the typedef looks like this: typedef float REAL; you don't have to make any changes to the source code, You can compile this application using the REAL type on each platform. The only thing to change is the typedef itself. In most cases, even this tiny change can be done automatically with wonderful conditional compilation. Isn't it? The standard library uses typedef extensively to create such platform-independent types: Size_t,ptrdiff and fpos_t are examples. In addition, typedef such as std::string and std::ofstream hide long, incomprehensible template-specific grammars, such as:basic_string,allocator> and basic_ofstream>.

typedef summary (from Wikipedia)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.