2013-03-26 43 views
11

我面對一個宏的問題,我不明白爲什麼。這個宏有什麼問題?

下面是宏:

#define WAIT(condition, max_time)    \ 
    do {           \ 
     int int_loop_wait=0;      \ 
     while(1)         \  
     {           \   
     if(condition) { break; }    \ 
     sleep(1);        \ 
     if(int_loop_wait>=max_time) { break; } \ 
     int_loop_wait++;      \ 
     }           \ 
    } while(0)         \ 

我得到了錯誤

「預期聲明」 行 「如果(條件){打破;}」

有誰理解這個錯誤?

+1

您不會更改循環內的'int_loop_wait'。 'max_time'沒有效果。 – Dipto 2013-03-26 11:12:50

+0

真的!我現在改變它。我保持你更新 – Joze 2013-03-26 11:13:37

+2

@ Krishnabhadra 這是一個宏,所以我不想要分號(它將被添加到代碼中) – Joze 2013-03-26 11:14:21

回答

24

問題是,反斜槓後跟一個空格被認爲是一個轉義序列,它實際上消除了反斜線。 Visual C++ 10甚至在那裏發出error C2017: illegal escape sequence

中的一些代碼段的線的(例如具有while(1)的一個)包含反斜槓之後的一個或多個空格。一旦反斜槓被視爲轉義序列並被編譯器刪除,宏定義將在該行被截斷,剩餘的代碼將被編譯爲不屬於宏定義。

#define WAIT(condition, max_time)    \ 
    do {           \ 
     int int_loop_wait=0;      \ 
     while(1)         \ <<<<<WHITESPACES 
     {           \<<<this line doesn't belong to macro 
     if(condition) { break; }    \<<<and neither does this 
     sleep(1);        \ 
     if(int_loop_wait>=max_time) { break; } \ 
     int_loop_wait++;      \ 
     }           \ 
    } while(0)         \ 
6

從最後一行

我的意思

} while(0) 

改變這一行

} while(0)              \ 

,並刪除所有空格\

後,你有一些行刪除\其中包含之後的空格喜歡:

while(1)         \  
     {           \   
+0

你說得對,但我仍然得到錯誤:/ – Joze 2013-03-26 11:18:40

+1

@Joze刪除'\\'後的所有空格。回答更新 – MOHAMED 2013-03-26 11:34:11

+0

任何想法爲什麼空間導致問題? – sharptooth 2013-03-26 11:40:21

5

罪魁禍首是空白\後。刪除它們將解決。

如果行以\結尾,宏定義將繼續,但不會與空間或任何其他字符結束。

#define WAIT(condition, max_time)         \ 
    do {               \ 
     int int_loop_wait=0;           \ 
     while(1){             \ 
     if(condition) { break; }         \ 
     sleep(1);             \ 
    if(int_loop_wait>=max_time) { break; }       \ 
     }               \ 
    } while(0)