2.4在宏中如何使用()
宏中每一个变量都必须要使用()把它们包围起来,这是为了支持表达式计算
否则编译器会编译我们意想不到的结果
例如:
#define SUM(x,y)((x)+(y))
#define MIN(x,y)((x)<(y)?(x):(y))
#define CUBE(x)((x)*(x)*(x))
完整代码演示
//demo.c
#ifdef __cplusplus
#include <iostream.h>
#else
#include <stdio.h>
#endif
demo(){
#ifndef _toupper(c)
#define _toupper(c) ((((c)>=’a’)&&((c)<=’z’)) ? (c) - ’a’ +’A’:c)
printf("_toupper(’b’)=%c\n",_toupper(’b’));
#else
#undef _toupper(c)
#endif
#define SUM(x,y)((x)+(y))
#define MUL(x,y)((x)*(y))
#define MIN(x,y)((x)<(y)?(x):(y))
#define MAX(x,y)((x)>(y)?(x):(y))
#define SQUARE(x)((x)*(x))
#define CUBE(x)((x)*(x)*(x))
printf("SUM(3,5)=%d\n",SUM(3,5));
printf("MUL(3,4)=%d\n",MUL(3,4));
printf("MIN(3,5)=%d\n",MIN(3,5));
printf("MAX(3,4)=%d\n",MAX(3,4));
printf("SQUARE(10)=%d\n",SQUARE(10));
printf("CUBE(10)=%d\n",CUBE(10));
}
main(){
demo();
}
责任编辑:小草