2015-10-08 41 views
-1

我打印一個字符串,如:的#define預處理器更換()字符串

printf("Print the number thirty: 30\n"); 

如果我做出如下定義

#define THIRTY 30 

現在

printf("Print the number thirty: THIRTY"); 

C預處理器替換字符串中的THIRTY --> 30

還是我必須去:

printf("Print then number thirty: %d", THIRTY); 
+6

怎麼樣,也許,很快嘗試? –

回答

2

C預處理器不理解什麼是內部字符串,因此不處理字符串。

下面的語句將取代THIRTY30

printf("Print then number thirty: %d", THIRTY); 
+0

如果你stringfy使用宏預處理器可以做到這一點... – LPs

+0

爲什麼投票呢?答案與問題問題一致。 –

1
printf("Print the number thirty: THIRTY"); // it will consider is whole as a string 

這將只是在輸出打印Print the number thirty: THIRTY

你的第二個說法 -

printf("Print then number thirty: %d", THIRTY); //you probably need this 

將打印 - Print then number thirty:30作爲輸出。

+0

如果你使用宏預處理器stringfy可以做到這一點... – LPs

+0

@LPs這不是重點。 OP想知道哪一個能按預期工作。所以答案就是這樣。 – ameyCU

+0

問題是C預處理器是否替換字符串中的THIRTY - > 30?預處理程序可以... – LPs

2

預處理器可以做到這一點,但你必須stringfy的定義。

#define xstr(s) str(s) 
#define str(s) #s 
#define THIRTY 30 
#define TEST "Print the number thirty: " xstr(THIRTY) "\n" 

int main() 
{ 
    printf(TEST); 
    return 0; 
} 

看看THIS