2012-05-20 30 views
0

如何將下面的代碼編譯正確,字符串化操作

#include <stdio.h> 
#define stringer(x) printf_s(#x "\n") 
int main() { 
stringer("In quotes when printed to the screen"); 
} 

是不是應該得到擴展到

printf_s(""In quotes when printed to the screen""\n"); 

這是因爲在printf_s嵌套雙引號的錯誤?

+0

順便說一句,在這個例子中,使用'puts'比'printf_s'。擁有更小的攻擊面比驗證層提供更高的安全性。 –

回答

3

沒有,#操作處理字符串字面量特別。它必須在傳遞給它的字符串文字中每個"轉義\。正確的膨脹是:

printf_s("\"In quotes when printed to the screen\"" "\n"); 
+1

它特別轉義字符*和*字符串文字。任何一種令牌都會引用引號和反斜槓。 – Potatoswatter

2

不,它擴展成

printf_s("\"In quotes when printed to the screen\"" "\n"); 

這將最終

printf_s("\"In quotes when printed to the screen\"\n"); 

,並應打印

"In quotes when printed to the screen" 
2

在C中,相鄰的字符串文字are concatenated

相鄰字符串文字是在編譯時級聯;這允許將長字符串拆分爲多行,並且還允許在編譯時將C預處理器定義和宏所產生的字符串文字附加到字符串:

+0

他似乎在故意使用它,這不是問題。 – Potatoswatter