2010-09-19 38 views
63
#define one 0 
#ifdef one 
printf("one is defined "); 
#ifndef one 
printf("one is not defined "); 

的作用,這是什麼#ifdef#ifndef的作用,什麼是輸出?的#ifdef和的#ifndef

回答

96

文本的ifdef/endififndef/endif內部將被留或通過根據狀況預處理器除去。 ifdef的意思是「如果定義如下」,而ifndef的意思是「如果以下是而不是定義的」。

所以:

#define one 0 
#ifdef one 
    printf("one is defined "); 
#endif 
#ifndef one 
    printf("one is not defined "); 
#endif 

等同於:

printf("one is defined "); 

因爲one定義所以ifdef是真實的ifndef是假的。不要緊,它的定義。類似的(我認爲更好的)這段代碼將會是:

#define one 0 
#ifdef one 
    printf("one is defined "); 
#else 
    printf("one is not defined "); 
#endif 

因爲它在這種特殊情況下更明確地指定了意圖。

在您的特定情況下,由於one已定義,因此ifdef之後的文本未被刪除。由於相同的原因刪除ifndef之後的文本是。有將需要在某個點二收盤endif線和第一會引起線開始被再次納入,具體如下:

 #define one 0 
+--- #ifdef one 
| printf("one is defined ");  // Everything in here is included. 
| +- #ifndef one 
| | printf("one is not defined "); // Everything in here is excluded. 
| | : 
| +- #endif 
| :        // Everything in here is included again. 
+--- #endif 
48

應該有人提到,在這個問題有一個小陷阱。 #ifdef只會檢查是否已通過#define或通過命令行定義了以下符號,但其值(其實際替代)無關緊要。你甚至可以寫

#define one 

預編譯器接受。 但是,如果您使用#if這是另一回事。

#define one 0 
#if one 
    printf("one evaluates to a truth "); 
#endif 
#if !one 
    printf("one does not evaluate to truth "); 
#endif 

會給one does not evaluate to truth。關鍵字defined可以獲得所需的行爲。

#if defined(one) 

因此相當於#ifdef

#if結構的優點是允許更好地處理代碼路徑,嘗試做類似的東西與老#ifdef/#ifndef對。

#if defined(ORA_PROC) || defined(__GNUC) && __GNUC_VERSION > 300 
0

「的#if一個」意味着如果「#定義一個」已被寫入「的#if一個」,「一個的#ifndef」被執行時,否則執行。

這只是C語言中if,then,else分支語句的C預處理器(CPP)指令的等價物。

即 if {#define one} then printf(「one evaluate to a truth」); else printf(「one is not defined」); 所以如果沒有#define one語句,那麼語句的else分支將被執行。

+3

我不確定這是什麼增加了其他答案尚未覆蓋,並且您的示例不是C或C++。 – SirGuy 2015-09-02 13:02:22