[問題] maco替換字符

看板C_and_CPP (C/C++)作者 (Immemorial)時間4年前 (2021/07/25 04:35), 4年前編輯推噓3(3013)
留言16則, 3人參與, 4年前最新討論串1/1
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

07/25 06:44, 4年前 , 1F
這裡用的是 C/C++ 裡當 string literal 併排時會合併的語法
07/25 06:44, 1F

07/25 06:44, 4年前 , 2F
例如你寫 "A" "B" "C" 和你寫 "ABC" 是一樣的意思
07/25 06:44, 2F

07/25 06:44, 4年前 , 3F
那這裡會是 "The square of " "y" " " 併排
07/25 06:44, 3F

07/25 06:45, 4年前 , 4F
其中 #x 如你所理解的變成了一個 string literal
07/25 06:45, 4F

07/25 06:45, 4年前 , 5F
然後套用這個合併語法就變成 "The square of y " 了
07/25 06:45, 5F

07/25 06:45, 4年前 , 6F
因此這裡並不是 #x 外面多一組引號
07/25 06:45, 6F

07/25 06:46, 4年前 , 7F
而是一個 string literal, 跟著 #x, 再跟著另一個 literal
07/25 06:46, 7F
嗯,感謝回答。 可是我還是無法明白下面這樣 #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

07/25 14:03, 4年前 , 8F
#被““包住 預處理時看不到吧
07/25 14:03, 8F

07/25 14:51, 4年前 , 9F
對, 就單純是 macro 不會代換 string literal 裡的東西
07/25 14:51, 9F

07/25 14:52, 4年前 , 10F
個人認為這個 string literal 併排規則其實就是解決這問題
07/25 14:52, 10F

07/25 14:52, 4年前 , 11F
才發展出來的語法...
07/25 14:52, 11F

07/25 14:54, 4年前 , 12F
string literal 裡的字編譯器除了會轉譯跳脫序列外只會照搬
07/25 14:54, 12F

07/25 14:55, 4年前 , 13F
這樣寫的人也不用擔心我寫的字串突然變了
07/25 14:55, 13F

07/25 14:55, 4年前 , 14F
那所以要代換 string literal 就需要一個在 "" 外的東西
07/25 14:55, 14F

07/25 14:56, 4年前 , 15F
這就是併排規則出場的時候了
07/25 14:56, 15F
嗯嗯,謝謝LP大大和其它人的熱心教導,我懂惹QQ ※ 編輯: ManOfSteel (101.10.94.202 臺灣), 07/26/2021 00:57:55

07/26 01:11, 4年前 , 16F
MACRO 不是MACO
07/26 01:11, 16F
※ 編輯: ManOfSteel (101.10.94.202 臺灣), 07/26/2021 01:52:16
文章代碼(AID): #1W_7cdiG (C_and_CPP)
文章代碼(AID): #1W_7cdiG (C_and_CPP)