Reprint--#define Usage

Source: Internet
Author: User
Tags define definition define function

Jency Lee

Links: http://www.cnblogs.com/Jency/articles/C_Cplusplus_define.html

1. Simple define Definition


#define MaxTime +

A simple maxtime is defined, which represents 1000 if you write in the program

if (i<maxtime) {...} The

Compiler replaces maxtime with 1000 before processing the code. The definition of

looks similar to a normal const definition, but it is also different because the definition of define is more like a simple text substitution than a volume, and this problem is particularly evident below.

2.define function definition

Define can accept parameters like a function, such as

#define MAX (x) > (y)? x):(y);

This definition will return the larger of the two numbers, see? Because this "function" does not have a type check, it is like a function template, of course, it is absolutely not as safe as a template. Can be used as a simple template.

However, there are hidden pitfalls, such as the following:
#define ADD (A, b) a+b;
There is no problem when it comes to general use, but if you encounter problems such as C * ADD (b) * d, the algebraic intent is to a+b and then to multiply with c,d, but because define is used (it's just a simple substitution), the formula actually becomes
C*a + b *d

Give another example:
#define PIN (int*);
Pin A, B; The
is intended to be a and B are int type pointers, but actually become int* a, a, A;
A is an int type pointer, and b is an int variable.
This should use typedef instead of define, so that both A and B are int pointers.

So when we define it, we develop a good habit of suggesting that all levels be bracketed.

3. Single-line definition of macros


#define A (x) t_# #x
#define B (x) #@x

#define C (x) #x
We assume that: X=1, there is:
A (1)------〉t_1
B (1)------ ' 1 '
C (1)------"1"

(referenced here Hustli's article)

4.define Multiline definition

Define can replace multiple lines of code, For example, the macro definition in MFC (very classic, although it makes people look disgusting)

#define MACRO (arg1, arg2) do {/
/* declarations */
STMT1;/
Stmt2;/
/* ... * */
} while (0)/* (no trailing;) */
The key is to add a "/"

Excerpt from http://www.blog.edu.cn/user1/16293/to each line break archives/2005/115370.shtml patched several bugs

5. In large-scale development processes, especially across platforms and systems, the most important feature of define is conditional compilation.

is:
#ifdef WINDOWS
...
...
#endif
#ifdef LINUX
...
...
#endif

Compiles the environment by # define at compile time

6. How to define macros, suppress macros

//define Macros
#define [ MacroName] [Macrovalue]
//Cancel Macro
#undef [MacroName]
Normal macro
#define PI (3.1415926)

Macro with parameters
#define Max (A, B) ((a) > (b)? (a), (b))
The key is that it is very easy to produce errors, including differences in machine and human understanding, and so on.

7. Conditional compilation


#ifdef XXX ... (#else) ... #endif
For example #ifdef dv22_aux_input
#define AUX_MODE 3
#else
#define AUY_MODE 3
#endif
#ifndef XXX ... (#else) ... #endif

8. The header file (. h) can be Beatles file or C file contains


Repeat include (repeat definition)
Because the header file contains can be nested, then the C file may contain multiple times the same header file, there may be a duplicate definition of the problem.
Avoid duplicate inclusions with conditional compilation switches (duplicate definitions)
For example
#ifndef __headerfilexxx__
# define __headerfilexxx__
...
File contents
...
#endif

9. #define中的 #, # # && #@

Some time ago when looking at the code of wince found in the macro definition is useful to # #, as shown below

#define GPEBLT_FUNCNAME (basename) (SCODE (GPE::*) (struct gpebltparms *)) &gpe::# #basename

In # define, the standard defines only # and # #两种操作. #用来把参数转换成字符串, # #则用来连接两个前后两个参数, turn them into a string.

1#define ToString (a) #a

2ToString (A b Cd); A b Cd

3ToString (a/n b Cd); A

4//b Cd

5ToString (a/n b Cd); A N B Cd

6

7

8#define ConCat (x, y) x # # Y

9ConCat ("ABC", "DEF");

10ConCat (123, 4);

11ConCat (123.0, 5);

12//=================================

13//Cat (123.0, 5.5);

14//Cat (' A ', ' B ');

15//Cat ("ABC", ' d ');

16//Cat (' a ', 1234);

17//Cat ("ABC", 1234);

18//===== above can ' t compile =======

19

20

In addition, search on the internet there is another way to use: #@, to convert the parameters into characters



1#define ToChar (a) #@a

2ToChar (a); A

3ToChar (AB); B

4ToChar (ABC); C

5ToChar (ABCD); D

6//tochar (ABCDE); Too many characters in constant

7ToChar (1.); // .

This is not seen on the standard. The above tests are done in the VS studio environment. Do not know if GCC has the same usage.




finally attach the difference between # define and typedef

1) #define是预处理指令, in the compilation preprocessing simple substitution, does not make the correctness check, does not have the meaning whether correctly still brings in, only when compiles the already expanded source program only then discovers the possible error 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) A 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 function is to use INT_PTR to represent the int *, but the two are different, as mentioned earlier, a simple substitution #define在预处理, whereas a typedef is not a simple substitution, but rather a type declared as a method of defining a variable. That is

Refer to (Xzgyb (Damour))
#define INT_PTR int *
INT_PTR A, B; equivalent to int * A, B; Just a simple macro replacement

typedef int* INT_PTR;
INT_PTR A, B; A, B is a pointer to int, and TypeDef introduces a new mnemonic for int*.


This also explains why the following ideas are set up
Qunkangli (Maintenance cost proportional to the square of Programmer's creativity)
typedef int * PINT;
#define PINT int *

So:
Const pint p;//p cannot be changed, but P points can be changed
The const PINT p;//p can be changed, but the content that P points to cannot be changed.

Pint is a pointer-type const pint p is a pointer to the lock p cannot be changed
The const PINT p is a const int * p Lock that is the object referred to by the pointer p.

4) It should also be noted that # define is not a statement do not add a semicolon at the end of the line, or a semicolon is replaced.

Add:

#elif

Equivalent to

#else

#if

Reprint--#define Usage

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.