C語言 函數和程序結構 宏替換#define


 宏定義的形式如下:

 

#define 名字 替換文本

這是一種最簡單的宏替換 —— 后續所有出現名字記號的地方都將被替換為 替換文本 。 #define 指令中的名字與變量名的命名方式相同,替換文本可以是任意字符串。通常情況下, #define 指令占一行,替換文本是 #define 指令行尾部的所有剩余部分內容,但也可以把一個較長的宏定義分成若干行,這時需要在待續的行末尾加上一個反斜杠符 \ 。 #define 指令定義的名字的作用域從其定義點開始,到被編譯的源文件的末尾處結束。宏定義中也可以使用前面出現的宏定義。替換只對記號進行,對括在引號中的字符串不起作用。例如,如果 YES 是一個通過 #define 指令定義過的名字,則在 printf("YES") 或 YESMAN 中將不執行替換。 替換文本可以是任意的,例如:

#define  forever  for (;;)    /* infinite loop */

該語句為無限循環定義了一個新名字 forever 。


宏定義也可以帶參數,這樣可以對不同的宏調用使用不同的替換文本。例如,下列宏定義定義了一個宏 max :

#define  max(A, B)  ((A) > (B) ? (A) : (B))

 

 

root@ubuntu:~/arm# vim test.c

#include<stdio.h>
void test2()
{

    printf("hello world \n ");
}
void show()
{ 

    printf("hello world show \n ");
}

//#define show test2
#define test2 show

int main()
{
     test2();
     show();
     return 0;
}

 

root@ubuntu:~/arm# gcc test.c -o test
root@ubuntu:~/arm# ./test
hello world show 
 hello world show 
 root@ubuntu:~/arm# ./test
hello world show 
 hello world show 
 root@ubuntu:~/arm# 

  

demo2

root@ubuntu:~/arm# cat test.c 

#include<stdio.h>
void test2()
{ 

    printf("hello world \n ");
}
void show()
{ 

    printf("hello world show \n ");
}

#define show test2
//#define test2 show

int main()
{
     test2();
     show();
     return 0;
}

 

 

root@ubuntu:~/arm# gcc test.c -o test
root@ubuntu:~/arm# ./test
hello world 
 hello world 
 root@ubuntu:~/arm# 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM