預(yù)處理命令
定義和使用宏
沒有參數(shù)的宏
#include <stdio.h>
# define MAX 100
# define INFO "Uozoyo best lover"
int main(){
printf("the integer is %d, the string is %s", MAX, INFO);
}
輸出如下:
the integer is 100, the string is Uozoyo best lover
帶參數(shù)的宏
#include <stdio.h>
# define MAX 100
# define INFO "Uozoyo best lover"
# define print(num, name) printf("the integer is %d, the string is %s", num, name)
int main(){
print(MAX, INFO);
}
輸出和上一節(jié)相同。
可選參數(shù)
使用省略號...表示可選參數(shù)。
# define var_print(...) printf("%s variable arguments is %s %s\n",__func__, __VA_ARGS__)
int main(){
var_print("peng", "xiong");
}
輸出為main variable arguments is peng xiong,其中__VA_ARGS__是將剩下的所有的參數(shù)都傳遞進(jìn)去。
字符串化運(yùn)算符
#被稱為字符串化運(yùn)算符(stringify operator),因?yàn)樗鼤?huì)把宏調(diào)用時(shí)的實(shí)參轉(zhuǎn)化為字符串。
# define printDBL(exp) printf(#exp "=%f ", exp) // 字符串化運(yùn)算符#
int main(){
printDBL(atan(1.0)*4);
}
輸出為atan(1.0)*4=3.141593
記號粘貼運(yùn)算符
token-pasting operator會(huì)把左右操作數(shù)結(jié)合在一起,作為一個(gè)記號。
# define TEXT_A "hello world, uozoyo." // 記號黏貼運(yùn)算符
# define msg(x) printf(TEXT_ ## x)
int main(){
msg(A); // 相當(dāng)于printf(TEXT_A);
}
輸出為hello world, uozoyo.。
在宏內(nèi)使用宏
宏不可以遞歸的展開。
宏的作用域和重新定義
undef
泛型宏
// Generic selection ----------BUG--------------not solved
# define peng_l(x) printf("i love u forever longtime double")
# define peng_f(x) printf("i love u forever float")
# define uozoyo(x) _Generic((x),\
long double: peng_l,\
float: peng_f,\
default: peng_f)(x)
這里寫出來的代碼時(shí)有問題的
有哥們實(shí)現(xiàn)了泛型棧,那個(gè)的話,就是可行的。https://blog.csdn.net/lovemylife1234/article/details/54918192
條件式編譯
# if defined(__GNUC__)
#pragma message("gunc")
# else
#pragma message("not gunc")
#endif
編譯出來的信息為
C:\Users\Administrator\Desktop>gcc test.c
test.c:5:11: note: #pragma message: gunc
#pragma message("gunc")
^~~~~~~
定義行號
# line 2000 "uozoyo.c" // 改變行號和文件名,這里其實(shí)可以和__LINE__和__FILE__對應(yīng)
int main(){
printf("file: %s ",__FILE__);
printf("line: %d",__LINE__);
}
輸出如下:file: uozoyo.c line: 2016即改變了原來的文件名和行數(shù)。
生成錯(cuò)誤消息
# ifndef __STDC__ // 生成錯(cuò)誤信息
# error "this compiler doesn't conform to the ANSI C standard."
#endif
生成錯(cuò)誤信息并退出。