【C++】惰性邏輯和臨時值以改善表示式的讀取

2021-01-26 C++

很抱歉,解釋性標題欠佳,我還找不到更好的名稱。

我習慣於對 bool(boolean) 表示式進行編碼,新增一些臨時變數以改善表示式的讀取,換句話說,我不喜歡這樣:

// Example 1
// hard to read and understand at first glance
if (value % 2 && value ^ weirdFlags &&
    (value > threshold) && (value < ceiling) &&
    /* lots of comparisions */)
{ /* do something*/ }

並且更喜歡這樣:
// Example 2
// this is way easier to read and understand
const bool isEven = value % 2;
const bool flagsChecked = value ^ weirdFlags;
const bool inRange = (value > threshold) && (value < ceiling);
const bool foo = /* lots of comparisions */;
if (isEven && flagsChecked && inRange && foo)
{ /* do something*/ }

但是使用我最喜歡的編碼方式,我沒有利用惰性邏輯優化,因為所有臨時值都被計算出來了,而使用其他編碼方式只計算了難以理解的程度。

還有另一種解決方案,允許使用惰性邏輯優化並保持程式碼可讀性,即註釋程式碼:
// Example 3
// this check test if the value is an even number
// and checks the value with the provided flags
// and assures that the value is in the required range
// and lots of additional comparisions
if (value % 2 && value ^ weirdFlags &&
    (value > threshold) && (value < ceiling) &&
    /* lots of comparisions */)
{ /* do something*/ }

但是在程式碼開發過程中,當一組程式設計師每天都在對同一原始檔進行編碼時,並沒有保證程式碼註釋與下面的程式碼匹配(並非所有編碼人員都在乎良好的文件)。這就是為什麼我認為程式碼以簡潔的方式說明自己。

因此,最後,研究示例2的情況,該示例將臨時值宣告為const,僅在 bool(boolean) 表示式中使用它們,且處於表示式的相同範圍內且與表示式本身接近,問題是:
  • 在示例2中,編譯器是否將執行涉及臨時值的某種優化,以提高 bool(boolean) 表示式的效能(惰性評估)?
  • 您認為以下三個示例中哪一個最正確?為什麼?

  • 謝謝你的建議。

    解決辦法

    看一下這個:

    if(const bool isEven = value % 2)
    if(const bool flagsChecked = value ^ weirdFlags)
    if(const bool inRange = (value > threshold) && (value < ceiling))
    if(const bool foo = /* lots of comparisions */)
    {
        /* do something*/
    }
    

    魔法!

    出處

    Have any Question?

    Let us answer it!