C語言 巨集定義的妙用

2021-10-23 11:06:28 字數 1662 閱讀 1744

在**中為了提高可讀性,把一些數字進行巨集標識化,同時也方便後續修改(一處修改,到處生效),

#define  year_count_sec    (365*24*60*60)ul

static u32 do_and_retry_try_cnt;

#define do_and_retry(func, target, try, success, fail) do \

else \

\} \

}while(0);

vcontrol name##ctrl=, \

0 \

};

/**

get event if event type.

@param[in] e event value.

@param[in] emin event minimum value.

@param[in] emax event maximum value.

@return

- @b true event is between minimun and maximun

- @b false event is out of range

*/#define in_range_event(e,emin,emax) (((e) > (emin)) && ((e) < (emax)))

#define max(x, y) ((x) > (y) ? (x) : (y))

#define min(x, y) ((x) < (y) ? (x) : (y))

字元連線:##

##操作可應用在變數定義中,若程式開發中遇到要定義一大堆變數,且這些變數具有相同的字首時,##很顯得尤為重要,它可以使**更加整潔,且減少了出錯的機率。同時,方便批量修改字首。

#include #define tokenpaster(n) printf ("token" #n " = %d\n", token##n)

int main(void)

輸出:token34 = 40

字串化:#

#include #define  message_for(a, b)  \

printf(#a " and " #b ": we love you!\n")

int main(void)

輸出:carole and debra: we love you!

#操作符可用於除錯時將變數名輸出,可配合##一起使用,

如定義#define check_var(x,fmt) printf(#x " = " #fmt "\n", x),則check_var(var1,%d)相當於printf("var = %d\n", var1);

就是將引數字元化

#define tochar(x)  #@x
如果a = tochar(b),那麼展開為:a = 'b';(可能早期編譯器不支援)

C語言巨集定義 , 巧妙用法

在我學習32的過程中發現了這樣一段 資訊輸出 define eeprom debug on 1 define eeprom info fmt,arg.printf eeprom info fmt n arg define eeprom error fmt,arg.printf eeprom erro...

c語言的巨集定義

include define square x x x define pr x printf the result is d.n x int main void 執行結果如下 the result is 16.the result is 4.the result is 14.the result i...

C語言巨集定義

c語言有很多預處理命令,如包含命令 include,巨集定義命令 define。預處理命令在程式編譯之前被編譯器處理,而巨集定義也在此時被替換。或c 語言源程式中允許用乙個識別符號來表示乙個字串,稱為 巨集 被定義為 巨集 的識別符號稱為 巨集名 在編譯預處理時,對程式中所有出現的 巨集名 都用巨集...