宏定义
带参数的宏定义,与函数很像,区别在于
(1)宏定义不涉及存储空间的分配、参数类型匹配、参数传递、返回值问题
(2)函数调用在程序运行时执行,而同替换只在编译预处理阶段进行。所以带参数的宏比函数有更高的执行效率。
1.
#include<stdio.h>
#define D(a) 2*a
int main()
{
int b = D(3+4);
printf("b is %d\n",b); //The calculation result would be 10 (10 = 2*3 +4), rather than 14. So the correct way to define D(a) is #define D(a) 2*(a);
return 0;
}
Output: b is 10
#include<stdio.h>
# define PI 3.14
int main()
{
float r,s;
printf("Pleas input the value of radius r:\n");
scanf("%f",&r);
s = 2 * PI * r;
printf("The length of this circle is %f\n",s);
return 0;
}
Input: 1
Output: The length of this cricle is 6.280000.
3. Conditional Compilation
#include<stdio.h>
#define M 11
int main()
{
#if M == 0
printf("M is 0\n");
#elif M > 0
printf("M is greater than 0\n");
#else
printf("M is smaller than 0\n");
#endif
return 0;
Other use:
(1) #if defined(M) or #if !defined(M) // It means if M has been defined before or not been defined before, the following codes would be compiled, until #endif is met.
...code...
#endif
(2) #ifdef M or #ifndef M or #if !defined(M) // The same with above explanation.
...code..
#endif