#define与typedef

Source: Internet
Author: User
Tags define definition

The #define (macro definition) is simply a string substitution (in-place extension), which itself is not performed during compilation, but before (the pre-processing process) is completed.

A typedef is a new name that is added to the identifier for readability (just an alias), and its new name has a certain encapsulation so that the newly named identifier has the ability to easily define the variable, which is part of the language compilation process, but it does not actually allocate memory space.

It is common to follow a # define definition of "readable" constants and the tasks of some macro statements, whereas a typedef is often used to define keywords, lengthy types of aliases.

typedef is a statement (ending with '; '), and # define is not a statement (not ending with '; ')

typedef (INT*) PINT;
and the following line:
#define PINT int*

Same effect? It's different!

See Differences in practice:

PINT A, B; the effect is the same as int * A; int * b; Represents the definition of two integer pointer variables a and b;

PInt A, B; the effect is the same as int * A; int b; Represents the definition of an integer pointer variable A and a shape variable B;

#define与const区别 (Define constants):

1. Const constants have data types, and # define (macro) constants have no data types. The compiler can perform type safety checks on the former. Instead of only character substitution, there is no type safety check, and the substitution of characters can produce unexpected errors (marginal effects).

2. The const constant allocates space on the stack, and the # define (macro) constant simply passes the specific value directly to the target variable. Or, the const constant is a run-time concept, and he really exists in the program and can be called and passed. The # define constant is a compile-time concept whose life cycle ends at compile time: in the actual program he is only a constant, a parameter in a command, there is no actual existence.

3. Const constants exist in the data segment of the program, #define常量存在于程序的代码段.

4. Some integrated debugging tools can debug const constants, but cannot debug macro constants.

#define的用法:

1. Simple macro definition

#define MaxTime 1000

A simple maxtime is defined, it stands for 1000, if it is written inside the program:

if (i<maxtime) {
}

The compiler replaces the maxtime with 1000 before processing the code.
Such a definition looks similar to the normal const definition, but it is also different because the definition of define is simply a substitution, rather than being used as a quantity, which is reflected in the following particular question.

2. Macros with parameters
Define can accept some parameters like a function, as follows:

#define Max (x, y) > (y)? (x):(y);

It will return the larger of the two numbers, and this "function" has no type checking, just like a function template, and of course, it is not difficult to see that it is absolutely not as safe as a template.
because of this, there are hidden dangers , examples are as follows:

#define Add (A, b) a+b;

The general use alone is not a problem, but if you encounter a problem such as: c * ADD (b) * d, the meaning of algebra is a+b and then multiplied with c,d, but because the use of define (it is only a simple substitution), so the formula actually becomes C*a + b*d.
Take another look at this example:

#define INT_PTR int *; int_ptr A, b;

Both A and B are int pointers, but they actually become

Int* A, B;

A is an int pointer, and b is a variable of type int. This should be defined using typedef:

int* int_ptr;int_ptr A, b;

So A and B are all int-type pointers.

3. Multi-line definition of define
Define can replace multiple lines of code, such as the macro definition in MFC (very classic, although it makes people look disgusting)

#define MACRO (arg1, arg2) do {/* * */////*    */  while (0*/*

4, in the large-scale development process, especially across the platform and system software, define the most important function is conditional compilation.

#ifdef WINDOWS ... .... #endif #ifdef LINUX ....... #endif

Compile environment can be set by # define at compile time

5. How to define macros and cancel macros

// Defining Macros #define [MacroName] [Macrovalue] // Cancel Macro #undef [MacroName] // Normal Macro #define PI (3.1415926)// macro #define with parameters  max (a) > (b)? (a), (b))

The key is to be very prone to errors, including differences in machine and human understanding, and so on.

6. Conditional compilation
#ifdef XXX ... (#else) ... #endif
For example:

#ifdef dv22_aux_input #define Aux_mode 3#else#define auy_mode 3#endif

#define和typedef的区别:

1, #define是预处理指令, in the compilation of pre-processing simple substitution, not for correctness check, whether the meaning is correct and so on, only when compiling the source program has been expanded to find possible errors and error. For example:
#define PI 3.1415926
In the program: Area=pi*r*r will be replaced with 3.1415926*r*r
If you write the number 9 in the # define statement as the letter G preprocessing is also brought in.

2. typedef is processed at compile time. It gives an alias to an already existing type within its scope, but you cannot use the typedef specifier inside a function definition.

3.

typedef int * INT_PTR;

And

#define INT_PTR int *

The effect is to use INT_PTR to represent int *, but they are different, as previously stated, #define在预处理时只是进行简单的替换, whereas typedef is not a simple substitution, but rather a type declared as a method of defining a variable. Repeat the previous example:

#define INT_PTR int *// equals int * A, b; just a simple macro substitution, A is an integer pointer, and b is an integer variable int *   //A, B is a pointer to int, and TypeDef introduces a new mnemonic for int*

4, you may have noticed that # define is not a statement, do not add a semicolon at the end of the line, or a semicolon will be replaced, but the typedef end must be semicolon, because it is a statement.

Four uses of typedef and two traps

Use one:
Defines an alias for a type, not just a simple macro substitution. Can be used as multiple objects that declare a pointer type at the same time. Like what:

Char*     PA,     PB;       //      The majority does not conform to our intent, it only declares a pointer to a character variable,   //     

The following are possible:

typedef     Char*     PCHAR;       //       PCHAR     PA,     PB;                   //     

Although:

Char     *PA,     

Also feasible, but relatively not in the form of TypeDef intuitive, especially in the need of a large number of pointers, the way typedef is more convenient.

Use two:
Used in the old C code (specific How old is not checked), to help the struct. In the previous code, when declaring a struct new object, you had to bring a struct with the form: struct struct name Object name, such as:

struct      tagPOINT1 {           int     x;            int struct tagPOINT1p1;              

In C + +, you can write directly: the name of the struct name object, which is:

TagPOINT1     

It is too much trouble to think that someone often writes a struct, so they invent:

typedef     struct     tagpoint {           int     x;            int      y;} Point; Point     p1;      //     

Perhaps, in C + +, this use of TypeDef is not very large, but understanding of it, to master the old code is still helpful, after all, we may encounter in the project earlier legacy code.

Use three:
Use typedef to define platform-independent types.
For example, to define a floating-point type called REAL, on the target platform one, let it represent the highest precision type:

typedef     Long     double     REAL;  

On platform two that does not support long double, replace the following:

typedef     Double     REAL;   

On three platforms that are not supported by double, replace the following:

typedef     Float     REAL;   

That is, when cross-platform, just change the typedef itself, do not make any changes to other source code.
This technique is widely used by the standard library, such as size_t.
In addition, because typedef defines a new alias for a type, it is not a simple string substitution, so it is more robust than a macro (although using macros can sometimes accomplish the above purposes).

Use four:
Define a new, simple alias for a complex claim. The method is: in the original declaration gradually replaced with the alias part of a complex declaration, so loop, the part with the variable name to the last substitution, get the original declaration of the most simplified version. Example:

1. Original declaration: Int * (*A[5]) (int, char*);
The variable name is a, and replacing a with a new alias Pfun is possible:

typedef     int     * (*pfun) (int,     Char*);   

The most streamlined version of the original statement:

Pfun     a[5

2. Original declaration: void (*b[10]) (void (*) ());
The variable name is B, replace the right part in parentheses, and Pfunparam as alias one:

typedef     void     

Replace the left variable B,pfunx with the alias two:

typedef     void     

The most streamlined version of the original statement:

Pfunx     b[

3. Original declaration: Doube (*) () (*e) [9];
Variable named E, replace the left part first, Pfuny as alias one:

typedef     Double

Replace the right variable E,pfunparamy with the alias two

typedef     PFUNY     (*pfunparamy) [9

The most streamlined version of the original statement:

Pfunparamy     E;   

Understand the "right-left" rule that is available for complex declarations: from the variable name, to the right, then to the left, the direction of the reading is reversed when the parentheses are analyzed, the parentheses are popped out of the brackets, or the left-to-right sequence is followed, until the entire declaration is parsed. Example:

int     (*func) (int     

First find the variable name func, there is a pair of parentheses outside, and the left is a * number, which means that func is a pointer, then jump out of this parenthesis, first look to the right, and also encounter parentheses, which means (*func) is a function, so func is a pointer to such a function, that is, a function pointer, Such functions have a formal parameter of type int*, and the return value type is int.

int     (*func[5]) (int     

The right side of the Func is a [] operator, stating that Func is an array with 5 elements, and the left side of the Func has a *, stating that the element of Func is a pointer (note that this is not the modifier func, but the func[5], because [] operator precedence is higher than *, and Func is preceded by [] Combined). Jumping out of this parenthesis, looking to the right, and encountering parentheses, the element of the Func array is a pointer to the function type, which points to a function that has a int* type parameter and a return value of type int.

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


Trap One:
Remember, TypeDef is a new alias that defines a type, unlike macro, which is not a simple string substitution. Like what:
Define first:

typedef     Char*     

And then:

int     MYSTRCMP (const     PSTR,     const     


is const PSTR actually equivalent to a const char*? No, it's actually equivalent to char* Const.
The reason is that const gives the entire pointer itself to be constant, that is, to form a constant pointer char* const.
Simply put, remember that when the const and typedef appear together, the typedef will not be a simple string substitution.

Trap Two:
A typedef is syntactically a keyword that stores a class (such as auto, extern, mutable, static, register, and so on), although it does not really affect the storage characteristics of an object, such as:

typedef     Static     int     INT2;     //

The compilation will fail with the hint "more than one storage class has been specified".

#define与typedef

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.