C語言在 define中使用 運算子和 運算子

2021-07-24 11:58:38 字數 1446 閱讀 8934

下面是乙個類函式巨集:

#define psqr (x) printf("the square of x is %d.\n",((x) * (x)));

如果這樣使用巨集:

psqr(8);

則輸出為:

the square of x is 64.

引號中的字串中的x被看作普通文字,而不是被看作乙個可被替換的語言符號。

1、利用巨集引數建立字串:#運算子

在類函式巨集的替換部分中,#符號用作乙個預處理運算子,它可以把語言符號轉化為字串。例如,如果x是乙個巨集參量,那麼#x可以把引數名轉化為相應的字串。該過程稱為字串化(stringizing)。例如:

#define #define psqr(x) printf("the square of  " #x " is %d.\n",((x) * (x)))

int main(void)

輸出如下:

the square of y is 25.

the square of 2 + 4 is 36.

第一次呼叫巨集時,用"y"代替#x;第二次呼叫巨集時,用"2  + 4"代替#x。ansi c的字串鏈結功能將這些字串與printf()語句中的其他字串組合以產生最終使用的字串。例如,第一次呼叫變成:

printf("the square of " "y" " is %d.\n",((y) * (y)));

接著,字串連線功能將這三個相鄰的字串轉換為乙個字串:

"the square of y is %d.\n"

2、預處理器的粘合劑:##運算子

和#運算子一樣,##運算子可以用於類函式巨集的替換部分。另外,##還可用於類物件巨集的替換部分。這個運算子把兩個語言符號組合成單個語言符號。例如:

#define xname (n) x ## n

這樣下面的巨集呼叫:

xname(4)

會展開成如下形式:

x4

程式如下:

#include #define sname (n) x ## n

#define print_xn (n) printf("x" #n " = %d\n", x ## n);

int main(void)

輸出如下:

x1 = 14

x2 = 20

關於在enum中使用 define的意義

real source attention 列舉型別定義時預設從0開始,如果沒有定義值的話,然後依次遞增。位於中間的話,則值為前乙個列舉值 1,如果沒有定義值的話。以下一段 來自於linux中的pthread.h enum 一直想不明白此處將 define放入enum有何意義?在進行一遍預處理後,也...

在C 中使用Queue

介紹 queue類執行將放在在queue中的物件採用先進先出的資料結構。物件從一端插入到佇列中從另一端移除。物件的順序程序使用queue queue介面 queue類實現了三個主要集合介面 icollection ienumerable和icloneable。queue的重要方法 queue類常用的...

在 C 中使用畫筆

出處 在 c 中使用畫筆 public class rectangle shape protected point m start protected point m end public rectangle point start,point end,color fgcolor m start s...