2017-05-31 47 views
-4

我在我的代碼中發現了一個錯誤。在開始一個switch語句的新案例之前,我簡單地忘記了break;。所以,代碼看起來像如何找到不中斷的案例;在switch語句中?

switch (nCounter) 
{ 
case 1: 
    *dReturnValue = 1.; 
    // here should have been a break; 
case 2: 
    *dReturnValue = 2.; 
    break; 
default: 
    *dReturnValue = 3.; 
    break; 
} 

如何我可以使用正則表達式來找到兩個例(或case ... default:)兩者之間沒有break;

感謝

菲利普

+6

任何像樣的編譯器都會提醒你。 –

+0

請參閱https://stackoverflow.com/questions/8809154/how-to-make-gcc-clang-warn-about-missing-breaks-in-switch-statements – stijn

+0

@πάνταῥεῖ而且在許多情況下,這是功能和預期行爲,而不是一個錯誤。 – i486

回答

0

最向後兼容回答你的問題是這樣的:

case(\n|[^bc]|c[^a]|ca[^s]|cas[^e]|b[^r]|br[^e]|bre[^a]|brea[^k])*case 

link :)

釋:

  1. 查找並使用單詞case
  2. 查看並使用除b以外的任何字母。
  3. 您也可以使用任何b,其後不跟r
  4. 同樣去br緊隨其後e等等直到break沒有k
  5. 如果後面緊跟單詞case,則使用從第一個字符開始的任何子字符串brea

評論:

這可以擴展到包括休息之後比空白和分號等什麼,但我只是想給你的總體思路(這意味着這將失敗case breakthrough case例如)。另外,case這個詞後面應該跟一個冒號。

+0

謝謝zehelvion。當我刪除第二個「案例」時,有搜索結果。當然,搜索結果並不是我一直在尋找的,但問題是,當我的Visual Studio凍結時,「?)」之後有什麼東西。有任何想法嗎? – Flippowitsch

+0

對不起,這是不正確的。只有在沒有搜索結果的情況下,VS纔會與第二個「case」一起凍結。 – Flippowitsch

+0

當沒有結果時,你測試了你的正則表達式嗎?我仍然無法使用它,因爲我的VS凍結。 – Flippowitsch

0

這是一種方法。有可能通過一些模板構建與開關/外殼相同的邏輯。

注意在每種情況下使用lambdas執行代碼。這確保只有一個代碼路徑被採用。

這是一個簡單的例子。請注意,在經過優化的版本中,這可能不會比開關/外殼更有效率。

#include <iostream> 

template<class T> 
struct Switcher 
{ 
    Switcher(T const& value) : value_(value) {} 

    template<class F> 
    auto On(T const& candidate, F&& f) -> Switcher& 
    { 
    if (not satisfied_ and candidate == value_) 
    { 
     satisfied_ = true; 
     f(); 
    } 

    return *this; 
    } 

    template<class F> 
    auto Otherwise(F&& f) 
    { 
    if (not satisfied_) { 
     satisfied_ = true; 
     f(); 
    } 
    } 

private: 
    T const& value_; 
    bool satisfied_ = false; 
}; 

template<class T> auto Switch(T const& value) 
{ 
    return Switcher<T>(value); 
} 

int main(int argc) 
{ 
    Switch(argc) 
    .On(1, []{ std::cout << "one arg\n"; }) 
    .On(2, []{ std::cout << "two args\n"; }) 
    .Otherwise([]{ std::cout << "more args\n"; }); 
} 
相關問題