2008-10-16 65 views
2

我曾經見過這個宏,但從未真正知道它的目的。任何人都可以闡明這一點嗎?_never_executed()的用途?

+1

你能找出它是如何定義的並添加到這個問題嗎? – 2008-10-16 12:10:52

回答

5

這是一個編譯器內在用於優化,通常在嵌入式編程中看到。我看到它使用的唯一時間是在switch語句的「default」中聲明該變量的範圍是有限的(爲了更好的優化)。例如:

/* Get DTMF index */ 
switch(dtmf) 
{ 
    case '0': 
    case '1': 
    case '2': 
    case '3': 
    case '4': 
    case '5': 
    case '6': 
    case '7': 
    case '8': 
    case '9': 
     /* Handle numeric DTMF */ 
     index = dtmf - '0'; 
     break; 
    case 'A': 
    case 'B': 
    case 'C': 
    case 'D': 
     index = dtmf - 'A' + 10; 
     break: 
    default: 
     _never_executed(); 
     break; 
} 

可能並不適用於所有的編譯器工作...

0

作爲測試的一部分,我已經看過類似的東西。如果它執行,那麼你知道你有一個錯誤。

1

我以前沒有見過它,但STFW與谷歌首先提出這個問題,然後一些其他參考。從它所說的話,這顯然是編譯器的暗示,代碼從未被執行 - 所以編譯器可以進行優化。它可以被合理地視爲將'assert(0)'置於其位置的藉口 - 因爲代碼永遠不會被執行,斷言永遠不會被觸發。當然,如果斷言確實觸發了,那麼你知道你有問題。

參見經典紙"Can't Happen or /* NOTREACHED */ or Real Programs Dump Core"

即使現在也值得一讀。

1

作爲一個僅供參考,MSVC有類似的東西(多一點靈活性),該__assume()內在。他們給出的一個例子:

int main(int p) 
{ 
    switch(p){ 
     case 1: 
     func1(1); 
     break; 
     case 2: 
     func1(-1); 
     break; 
     default: 
     __assume(0); 
      // This tells the optimizer that the default 
      // cannot be reached. As so, it does not have to generate 
      // the extra code to check that 'p' has a value 
      // not represented by a case arm. This makes the switch 
      // run faster. 
    } 
} 

我不確定哪個版本的MSVC首次被支持。