定义一个简单的宏:
#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__宏用来接受不定数量的参数。
将宏参数转换为字符串,即加上双引号。
对空格有特殊处理:
#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";