编译指令

#define

定义一个简单的宏:

#define MAX(a, b) ((a) < (b) ? (b) : (a))

///抑或一段简单的代码
#define SWAP(a, b)  { a ^= b; b ^= a; a ^= b; }

///再换个行吧
#define SWAP(a, b)  {                   \\
                        a ^= b;         \\
                        b ^= a;         \\
                        a ^= b;         \\
                    }

/// 多个参数是怎样的?
#define debugPrintf(...) printf("DEBUG: " __VA_ARGS__);
debugPrintf("Hello World!\\n");						//DEBUG: Hello World!

int x=12;
int y=13;
debugPrintf("x=%d, y=%d\\n", x, y);					//DEBUG: x=12, y=13

特殊符号

\

换行符,注意最后一行不需要。

VA_ARGS

__VA_ARGS__宏用来接受不定数量的参数。

将宏参数转换为字符串,即加上双引号。

对空格有特殊处理:

  1. 忽略传入参数名前面和后面的空格。
  2. 当传入参数名间存在空格时,编译器将会自动连接各个子字符串,用每个子字符串中只以一个空格连接,忽略其中多余一个的空格。
#define ToString(x) 	#x
char* str = ToString(happy coding);					//str="happy coding";
char* str = ToString(happy    coding);					//str="happy coding";
char* str = ToString(     happy    coding    );					//str="happy coding";

token-pasting,符号连接操作符。而##的作用则是将宏定义的多个形参成一个实际参数名。

#define ConnnectionXY(x,y) 	x##y

int n = ConnnectionXY(123,456); 					// n=123456;
char* str = ConnnectionXY("asdf", "adf");		    // str = "asdfadf";

#@