看板 C_and_CPP 關於我們 聯絡資訊
Hi 我想請問一下 (1) #define B(z) #z char *string=B(HELLO); void main() { printf("%s\n",string); } 因為根據 C primer plus的說法,會形成有雙引號的HELLO,展開如下: char *string="HELLO"。 螢幕顯示結果:HELLO 可是C primer plus有一個範例如下: (2) #define PSQR(x) printf("The square of " #x " ") void main() { PSQRY(y); } 螢幕顯示結果:The square of y 問題: #x 旁為啥會多一組雙引號,形成" #x "。 如果不加雙引號,結果就會是: The square of #x 為什麼呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.10.94.202 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1627158951.A.B10.html ※ 編輯: ManOfSteel (101.10.94.202 臺灣), 07/25/2021 04:37:40 ※ 編輯: ManOfSteel (101.10.94.202 臺灣), 07/25/2021 04:51:18
LPH66: 這裡用的是 C/C++ 裡當 string literal 併排時會合併的語法07/25 06:44
LPH66: 例如你寫 "A" "B" "C" 和你寫 "ABC" 是一樣的意思07/25 06:44
LPH66: 那這裡會是 "The square of " "y" " " 併排07/25 06:44
LPH66: 其中 #x 如你所理解的變成了一個 string literal07/25 06:45
LPH66: 然後套用這個合併語法就變成 "The square of y " 了07/25 06:45
LPH66: 因此這裡並不是 #x 外面多一組引號07/25 06:45
LPH66: 而是一個 string literal, 跟著 #x, 再跟著另一個 literal07/25 06:46
嗯,感謝回答。 可是我還是無法明白下面這樣 #define PSQR(x) printf("The square of #x ") 為什麼#x不會替換成y,反而是輸出下面結果 The square of #x ※ 編輯: ManOfSteel (101.10.94.202 臺灣), 07/25/2021 13:46:39
chuegou: #被““包住 預處理時看不到吧07/25 14:03
LPH66: 對, 就單純是 macro 不會代換 string literal 裡的東西07/25 14:51
LPH66: 個人認為這個 string literal 併排規則其實就是解決這問題07/25 14:52
LPH66: 才發展出來的語法...07/25 14:52
LPH66: string literal 裡的字編譯器除了會轉譯跳脫序列外只會照搬07/25 14:54
LPH66: 這樣寫的人也不用擔心我寫的字串突然變了 07/25 14:55
LPH66: 那所以要代換 string literal 就需要一個在 "" 外的東西07/25 14:55
LPH66: 這就是併排規則出場的時候了07/25 14:56
嗯嗯,謝謝LP大大和其它人的熱心教導,我懂惹QQ ※ 編輯: ManOfSteel (101.10.94.202 臺灣), 07/26/2021 00:57:55
fatrabitree: MACRO 不是MACO 07/26 01:11
※ 編輯: ManOfSteel (101.10.94.202 臺灣), 07/26/2021 01:52:16