The use of typedef and #define and the distinction between _c languages

Source: Internet
Author: User
Tags define definition

The use of a typedef

In C/s + + language, a typedef is commonly used to define an identifier and a keyword alias, which is part of the language compilation process, but it does not actually allocate memory space, as in the case of:

typedef int INT;
typedef int ARRAY[10];
typedef (int*) pint;

A typedef enhances the readability of the program, as well as the flexibility of the identifier, but it also has drawbacks such as "not intuitive".

Second, #define的用法

#define为一宏定义语句, it is often used to define constants (including parameters and parameters), and to implement "seemingly benign, long behind a string" of macros, which itself is not carried out in the compilation process, but before this (the pre-processing process) has been completed, However, it is difficult to identify potential errors and other code maintenance issues, and its examples are as follows:

#define INT int
#define TRUE 1
#define ADD (A,b) ((a) + (b));
#define LOOP_10 for (int i=0; i<10; i++)

In the effective C + + Book of Scott Meyer, article 1 has an analysis of the drawbacks of the #define statement, as well as a good alternative, you can see.

Iii. the difference between the typedef and the #define

It is also clear from the above concept that the typedef is simply a new name for the identifier (just an alias) to increase readability, whereas #define was originally in C to define constants, to C++,const, enum, The advent of inline has made it an alias tool. Sometimes it is easy to confuse with the typedef which is the best to use, such as #define INT int, such as statements, with a typedef can be completed, which is good? I advocate using TypeDef, because this statement is illegal in many of the early C compilers, but today's compilers are expanding. In order to be as compatible as possible, the #define definition of "readable" constants and the tasks of some macro statements are generally followed, and typedef is often used to define keywords, verbose type aliases.

A macro definition is simply a string substitution (in-place extension), and a typedef is not an in-place extension, and its new name has a certain encapsulation so that the newly named identifier has the ability to define variables more easily. Take a look at the third line of the first big point code above:

typedef (int*) pint;
and the following line:
#define PINT2 int*

Same effect? actually different! In practice, see the difference: pint a,b effect with int *a; int *b; indicates that two integer pointer variables are defined. And the effect of pINT2 a,b with int *a, B;

Indicates that an integer pointer variable A and integral variable B are defined.

Four uses of the typedef and two traps

Purpose One:
defines a type of alias, not just a simple macro substitution. Can be used as multiple objects that declare a pointer type at the same time. For example:
char*   pa,   pb;    //   This majority does not conform to our intent, it declares only a pointer to a character variable.   
//   and a character variable;
This works:
typedef   char*   pchar;     //   general use uppercase
pchar   pa,   pb;                 //   feasible, and declared two pointers to character variables
although:
Char    *pa,   *PB;
is also feasible, but is relatively not intuitive in the form of a TypeDef, especially where a large number of pointers are needed, and the way of TypeDef is more convenient.

Use two:
Used in the old C code (the specific old did not check), to help struct. In previous code, when declaring struct a new object, you must take a struct, in the form of a struct struct name object name, such as:
struct TAGPOINT1
{
int x;
int y;
};
struct tagPOINT1 p1;

In C + +, you can write directly: a struct name Object name, which is:
TagPOINT1 P1;

Someone who thinks it's too much trouble to write a struct too often, then invents:
typedef struct TAGPOINT
{
int x;
int y;
}point;

Point P1; This is less than the original way to write a struct, more convenient, especially in the mass use of the time

Perhaps, in C + +, the use of a typedef is not very large, but understanding it is useful for mastering old code, after all, we may encounter earlier years of code left over in the project.

Use three:
Use typedef to define platform-independent types.
For example, to define a floating-point type called real, on the target platform, let it represent the highest precision type:
typedef long double Real;
On Platform II, which does not support long double, replace the following with:
typedef double REAL;
On a platform not supported by double, replace the following:
typedef float REAL;
In other words, when cross-platform, just change the typedef itself on the line, do not make any changes to other source code.
The standard library uses this technique extensively, such as size_t.
In addition, because TypeDef is a new alias that defines a type and is not a simple string replacement, it is more robust than a macro (although the use of macros can sometimes do the above).

Use four:
Define a new simple alias for a complex declaration. The method is to replace a part of the complex declaration with an alias in the original declaration, so that the loop takes the part with the variable name to the last replacement and gets the simplest version of the original declaration. Example:

1. Original declaration: Int * (*A[5]) (int, char*);
Variable named a, replace a directly with a new alias Pfun:
typedef int * (*PFUN) (int, char*);
The most simplified version of the original declaration:
Pfun A[5];

2. Original declaration: void (*b[10]) (void (*) ());
Variable name B, first replace the right part of the bracket, Pfunparam for alias one:
typedef void (*pfunparam) ();
Replace the left variable B,pfunx to alias two:
typedef void (*PFUNX) (Pfunparam);
The most simplified version of the original declaration:
Pfunx B[10];

3. Original declaration: Doube (*) () (*e) [9];
Variable name e, replace the left part first, Pfuny is alias one:
typedef double (*pfuny) ();
Replace the right-hand variable E,pfunparamy with the alias two.
typedef PFUNY (*pfunparamy) [9];
The most simplified version of the original declaration:
Pfunparamy e;

Understand the "right left" rule available for complex declarations: from the variable name look, first to the right, and then to the left, a round of parentheses to turn the reading direction; After parsing in parentheses, jump out of parentheses, or in the order of the first right and left, so cycle until the entire statement is analyzed. Example:
Int (*func) (int *p);
First find the variable name func, there is a pair of parentheses outside, and a * number on the left, which means that func is a pointer, then jumps out of the parentheses, looks to the right, and then encounters parentheses, which means that (*FUNC) is a function, so func is a pointer to such a function, the function pointer, Such functions have formal parameters of the int* type, and the return value type is int.
Int (*func[5]) (int *);
Func to the right is an [] operator, description func is an array of 5 elements; func has a * on the left, indicating that the Func element is a pointer (note that the * is not cosmetic func, but is decorated func[5] because [] operator precedence is higher than *, Func first with [] Combined). Jump out of this bracket, look to the right, and also encounter parentheses, stating that the element of the Func array is a pointer to a function type, which points to a function that has a int* type parameter, and the return value type is int.

You can also remember 2 modes:
Type (*) (...) function pointers
Type (*) [] array pointer

---------------------------------

Trap One:
Remember, a typedef is a new alias that defines a type, and unlike macro, it is not a simple string replacement. Like what:
First define:
typedef char* PSTR;
And then:
int mystrcmp (const PSTR, const PSTR);

is the const PSTR actually equivalent to the const char*? No, it's actually equivalent to char* Const.
The reason is that const gives the whole pointer itself a constant, that is, a constant pointer char* const.
In short, remember that when the const and the typedef appear together, the typedef is not a simple string replacement.

Trap Two:
A typedef is syntactically a storage class keyword (like auto, extern, mutable, static, register, etc.), although it does not really affect the storage characteristics of the object, such as:
typedef static INT INT2; Not feasible
Compilation will fail, prompting "more than one storage class specified."

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.