[問題] Token pasting (token paste)

看板C_and_CPP (C/C++)作者 (懂的付出才會幸福)時間16年前 (2010/04/30 17:24), 編輯推噓2(204)
留言6則, 4人參與, 最新討論串1/2 (看更多)
遇到的問題: (題意請描述清楚) 以sprintf為例 token pasting練習 針對第一個warning message以及所跑出來的結果 沒有頭緒 想請教 是哪邊有錯誤 希望得到的正確結果: (1)__ (2)__ 0 (3)__ 程式跑出來的錯誤結果: (1)__ (2)__ -374100824 , i(3)__ 請按任意鍵繼續 . . . 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) Visual Studio 2005 有問題的code: (請善用置底文標色功能) #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define MY_PRINTF(buf, format) sprintf(buf,##format) int main() { int i = 0; char str[100]; printf("(1)__\r\n"); MY_PRINTF(str, "%d\r\n, i"); printf("(2)__\r\n"); printf(str); printf("(3)__\r\n"); return 0; } 補充說明: complie warning message main.c(13) : warning C4313: 'sprintf' : '%d' in format string conflicts with argument 1 of type 'char [100]' main.c(9) : warning C4189: 'i' : local variable is initialized but not referenced -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.251.160.61

04/30 17:32, , 1F
你認為macro展開後如何?
04/30 17:32, 1F

04/30 17:44, , 2F
sprintf(str, %d\r\n, i) 嗯...這樣不對
04/30 17:44, 2F

04/30 17:45, , 3F
MY_PRINTF(str, "\"%d\r\n\", i"); 好像也不行
04/30 17:45, 3F

04/30 18:28, , 4F
甚麼是 token past ? @__@
04/30 18:28, 4F

04/30 18:29, , 5F
啊~~~ 應該是token paste (token pasting)
04/30 18:29, 5F

04/30 18:33, , 6F
你可以想一下printf是輸出啥
04/30 18:33, 6F
文章代碼(AID): #1Bsg6yLb (C_and_CPP)
文章代碼(AID): #1Bsg6yLb (C_and_CPP)