zoukankan      html  css  js  c++  java
  • C:宏定义的一些格式(怕忘记)

    现在还没怎么用到宏定义,但以后肯定会经常用的,写下这盘,以后忘记了可以温故。首先宏定义必须写在函数之外,其作用域从宏定义命令起到源程序结束,也就是说一但定义系统就会分配内存,想让它结束用“#undef“命令,格式如下:#define 标识符 字符串,记住不能加封号,假如宏名在源程序中用双引号括起来,则已成为字符串中的字符,预处理程序不对其进行宏替换,例子:

    1 #include "stdio.h"
    2 #define OK 100
    3 void main()
    4 {
    5     printf("OK");
    6 }

    其结果还是为:OK。宏定义还允许嵌套,比如:#define p 1314   #define q p*p,用宏定义可以简单化你的代码,至少打的字少很多,假如我们要输出五个数并且要换行,是不是要打五个%d和 ,现在用宏定义试一下:

     1 #include "stdio.h"
     2 #define x "%d
     3 #define y  
    
     4 #define x1 %d
     5 #define y1 
    "
     6 void main()
     7 {
     8     int a=1,b=2,c=3,d=4;
     9     printf(x y x1 y x1 y x1 y1,a,b,c,d);
    10 } 

    从代码可以看出x y x1 y x1 y x1 y1=="%d %d %d %d ",但是结果是不能运行的,这说明我们不能一一代入,还是要尊重下宏定义的规则,例如这样:

    1 #include "stdio.h"
    2 #define x "%d"
    3 #define y "
    "
    4 void main()
    5 {
    6     int a=1,b=2,c=3,d=4;
    7     printf(x y x y x y x y,a,b,c,d);
    8 }

    这样就可以运行。宏定义还可以定义一些简单的函数,格式如下:#define 宏名(形参表) 字符串,来做个比较容易混淆的例子:

    1 #include "stdio.h"
    2 #define SQ(y) y*y
    3 main()
    4 {
    5     int a,b;
    6     scanf("%d",&a);
    7     b=SQ(a+1);
    8     printf("%d",b);
    9 }

    运行结果:,一开始我以为是16,但是其运行过程是:a+1*a+1;因为上面宏定义是y*y,当我们把y*y改成(y)*(y),其结果是:

    其中运行过程是:(3+1)*(3+1)=16.

  • 相关阅读:
    queue
    hiho1095(二分)
    uvaliva3942(trie树)
    hiho1014(trie树)
    uvalive4329(树状数组)
    Dropping tests POJ
    linux mysql命令
    linux文件系统和mount(硬盘,win分区,光驱,U盘)
    linux共享windows资料
    linux常用命令
  • 原文地址:https://www.cnblogs.com/doudoublog/p/5062149.html
Copyright © 2011-2022 走看看