c++ - 惰性逻辑和临时值以提高表达式的可读性

标签 c++ coding-style lazy-evaluation

抱歉,解释性不佳的标题,我(目前)找不到更好的标题。

我习惯于编写 bool 表达式,添加一些临时变量来提高表达式的可读性,换句话说,我不喜欢这样:

// 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*/ }

但是在代码开发过程中,当一组程序员每天都在编写相同的源文件时,并不能保证代码注释与下面的代码匹配(并不是所有的编码人员都关心好的文档)。这就是为什么我更喜欢代码以简洁的方式 self 解释的原因。

最后,研究示例 2 的情况,将临时值声明为 const,仅在 bool 表达式中使用它们,在表达式的相同范围内并接近表达式本身,问题是:

  • 在示例 2 中,编译器是否会执行某种涉及临时值的优化以提高 bool 表达式的性能(惰性求值)?
  • 在您看来,这三个示例中哪个最正确?为什么?

感谢您的建议。

最佳答案

检查一下:

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*/
}

魔法!

关于c++ - 惰性逻辑和临时值以提高表达式的可读性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16537487/

相关文章:

c++ - ld : duplicate symbol 的原因是什么

c++ - Libharu pdf 创作 : How to know the size of the printed text

wolfram-mathematica - Mathematica 7 是否支持惰性求值?

python - 在 Python 中延迟初始化的字符串

Haskell: "cache"如何友好是 Lazy Eval/按需调用

c++ - 有没有办法在 Visual Studio 2019 中加载当前 .cpp 文件的 .h 文件?

c++ - ASM I/O 引脚 HCS12 微 Controller

c - 在结构中使用指针和零元素数组的区别

java - 在内存中加载文本文件的最快/最干净的方法

c++ - 故意崩溃的代码