短路和可读性

leg*_*s2k 2 c conditional if-statement readability short-circuiting

在这一行

if ((last_search == NULL) || (last_search != NULL && total_results != 0))

我知道C的短路评估规则说只有当last_search它不为空时才会尝试并评估右侧||,因此它等同于写作

if ((last_search == NULL) || (total_results != 0))

而且我被建议使用后来的某人,但前者仍然不是更具可读性吗?编译器也不会优化冗余last_search != NULL吗?

Jon*_*Jon 10

这是主观的,但不是,第一个变体不具有可读性,因为还有更多要阅读.最可读的代码(和最少的错误!)是不存在的代码.试想一下,如果你想一次检查3个或4个条件会发生什么.

这是另一个反例:你会写这样的代码吗?

if (number < 0) {
}
else if(number >= 0) {
    // why not just "else"?
}
Run Code Online (Sandbox Code Playgroud)

至于性能:编译器可能会优化冗余调用,但撤消性能下降无助于可读性降低.


Luc*_*ore 5

不,这不对.第二个是更具可读性.无论编译器是否会对其进行优化,为什么还要在那里保留冗余校验?

第一个版本告诉你,这last_search不是NULL因为它到达那里,但如果你不能从第一个条件(last_search == NULL失败)告诉你,你可能会遇到比可读性更大的问题.