星期六, 五月 19, 2007

#define conclusion

Macro can be thought as a mechanism of replacement in C++.

1. Basic #define
We can use it as a way of text replacement.

#define POPULATION 1200000

When we are compiling it, we will replace every POPULATION to 1200000 in the following code.

2. Function Definition
#define can receive parameters as Funcitons.

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

This function returns the bigger number. However, since without type detectation, it's more like funciton template. But there is still some fault.
For example:

#define ADD(a,b) a+b;

When you encounter code c*ADD(a,b)*d, the factual calculating process becomes c*a+b*d, not c*(a+b)*d. That's a big problem

Another emaple:

#define pin(int*);
pin a, b;


When you call the macro, you mean to indicate both a and b are int pointers. But factually, it is int*a, b, which means a is an int pointer, but b is int

type. Therefore, you should use another way typedef to replace define.


3. Macro Single line Definition

#define A(x) T_##x

if x = 1, then A(1) ======== T_1

You must be surprised by the result. Here "##"means combination. When you call this macro, the result is to combine T_ and x. Here x=1, so the result is T_1.

4.Macro Multilines Definintion

Many lines of #define is available. In MFC, this kind of method is constantly used.

#define MACRO(arg1, arg2) do { \
/* declarations */ \
stmt1; \
stmt2; \
/*........*/ \
} while(0) /* (no trailing ; ) */

Do not forget to add "/" after every line.

5.Condition Compiling

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


You can #define to setup compiling enviroment.

5. How to define Macro and cancel Macro

//定义宏
#define [MacroName] [MacroValue]
//取消宏
#undef [MacroName]
//普通宏
#define PI (3.1415926)
//带参数的宏
#define max(a,b) ((a)>(b)? (a),(b))


6.Macro combination

## is to combine two macros
# is to replace the name with string

For example

#define s5(a) supper_ ## a
#include
void supper_printf(const char* p )
{
printf("this is supper printf:\n%s\n",p);
}

int main()
{
s5(printf)("hello owrld");
return 0;
}

Result:
This is supper printf:
hello world

Example
#include
#define s(p) #p

int main()
{
printf(s(p)"\n");
return 0;
}

Result:
p

# can be uesd to constrain it a parameter to become a string.

没有评论: