现在还没怎么用到宏定义,但以后肯定会经常用的,写下这盘,以后忘记了可以温故。首先宏定义必须写在函数之外,其作用域从宏定义命令起到源程序结束,也就是说一但定义系统就会分配内存,想让它结束用“#undef“命令,格式如下:#define 标识符 字符串,记住不能加封号,假如宏名在源程序中用双引号括起来,则已成为字符串中的字符,预处理程序不对其进行宏替换,例子:
#include "stdio.h"
#define OK 100
void main()
{
printf("OK");
}
其结果还是为:OK。宏定义还允许嵌套,比如:#define p 1314 #define q p*p,用宏定义可以简单化你的代码,至少打的字少很多,假如我们要输出五个数并且要换行,是不是要打五个%d和\n,现在用宏定义试一下:
#include "stdio.h"
#define x "%d
#define y \n
#define x1 %d
#define y1 \n"
void main()
{
int a=,b=,c=,d=;
printf(x y x1 y x1 y x1 y1,a,b,c,d);
}
从代码可以看出x y x1 y x1 y x1 y1=="%d\n%d\n%d\n%d\n",但是结果是不能运行的,这说明我们不能一一代入,还是要尊重下宏定义的规则,例如这样:
#include "stdio.h"
#define x "%d"
#define y "\n"
void main()
{
int a=,b=,c=,d=;
printf(x y x y x y x y,a,b,c,d);
}
这样就可以运行。宏定义还可以定义一些简单的函数,格式如下:#define 宏名(形参表) 字符串,来做个比较容易混淆的例子:
#include "stdio.h"
#define SQ(y) y*y
main()
{
int a,b;
scanf("%d",&a);
b=SQ(a+);
printf("%d",b);
}
运行结果:aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAm8AAACBCAIAAAAZhcoEAAALwklEQVR4nO3dWZbaxh7H8VpGFsCDt8Izp5fBAnjODvqdDfRrbhzHSfDQ7Z7dg3tyj/RgO7aTe7fAfRBINVPSHwSY7+fo+IAQpVJJqh8qQVudfflfNp1+/u/Jp39PPv178vTPh8fvx4/fjh6+Ht5/Pbj7sn/zaffqYfP8bv3k6vXhxauDs7/2T/7YPX65c/T79uGLrYMXm+9/e7f/fGPv+cberxu7TExMTExMSzWpPEpP8yh9+n78+P3o4dvR/dfD/t/vbz/vXj1uXdytn1z99PMFExMTExMTkzWZ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cBcrW05iY4baP3118ap628F9HNplAGaPNK1NYscdX1h/NfSusjmUkhwV0s7b71dIr8StqFZOhfokNl2pqnrbObIiAHOHNK1NYscdX7hygZFlppqm8XWFCiRN4ysCMHdI09pI0nRsqklSJCU5KqRdqXIqlO99u6QdEstJaTp3vfE53jcm7iMAc4E0rceaJmW+9ZLbk6bPH1slldaJrzkSC4+XE6p/yia4K5K0Q2I5oe0K1UcF9vLY9gnNT28cAPUhTVHBtDt0AgPAgiFNURZROj/WAmZdL2D5kKZIMe3OmjCohjQF5gVpCgCAFGkKAIAUaQoAgBRpCgCAFGkKAIAUaQoAgBRpCgCAFGkKAIAUaQoAgBRpCgCAFGkKAIAUaQoAgBRpCgCAFGkKAIAUaQoAgBRpCgCAFGkKAIAUaQoAgBRpCgCAFGkKAIAUaQoAgBRpCgCAFGkKAIDQ/wFtWicQtT0bSAAAAABJRU5ErkJggg==" alt="" />,一开始我以为是16,但是其运行过程是:a+1*a+1;因为上面宏定义是y*y,当我们把y*y改成(y)*(y),其结果是:aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAANMAAABNCAIAAACzCca9AAAIIUlEQVR4nO1a61ITSRQ+j+EDzA9eJb9TPMY8QKp0V0XEu5jdvyn3Iut611XuGpcVuSRcQkgIJCQhISAgulVeWFdXZ3/0ZNIzfZnJMEmLnK++onpOnznTffqb7ukm8GP8b5pLL5DIdhBQeUglROUh1RCVh1RDd+VlN1+3mgBfAL604UHIr4em8n548pqQ41GXhUgf3nVDPFn/lioPKHix07Xe4/tr1cGNH8C4WJpjlZfZeJXZeAXwGeAzXXBQZPfnFixJWr2XRRbvTzkM/sEMjV15bJs+A/znYKa2m6ntco0Ou2W07LTF1dm1yhGNpZlTqZ31kVu8+DfbKh/xSQroQtvaHwiJ8l5Z5KXpE8CnxfWXVsFHmb2kyVb5iC8iSavE6HBo1l9iDKQ9EuMnkgK7vdXtD4pABBd9vEu4WNulq9PrOwAfAT7SBd9lmsTOevqLLydJq8jiqGWd5f4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