在 C++ 中使用嵌套 if 语句与逻辑运算符 &&

Using nested if statements vs logical operator && in c++

假设我有一个整数数组代表棋盘上的棋子;

int board[8][8];

在我的国际象棋游戏中,我目前正在编写一个生成器函数,它将return一个整数向量所有合法动作。

当然,我会使用 if 语句

我现在需要检查棋盘中的某个元素相对于棋盘上的某个元素

例如,如果我有一个棋子;

board[row][col] == 'p';

我需要生成 [row+1][col][row+2][col] 并且在某些情况下如果它可以攻击一块,也会更改列。

但是如果一个棋子在board的任何边上,board[row+1][col]将return index out of range

出于这个原因,我需要一个额外的 if 语句。

我的问题是,我应该使用:

if (pieceisnotonedge && board[row+1][col] == 0)

if (pieceisnotonedge)
{
    if (board[row+1][col] == 0)
}

第一个例子,如果pieceisnotonedge returns false,是否还会检查下一个条件?因为如果是这样,那我就有麻烦了。

For the first example, if pieceisnotonedge returns false, will it also check the next condition?

没有。它会在 pieceisnotonedge 被评估为 false 后立即停止。没有后续检查余数条件board[row+1][col] == 0

您也可以使用嵌套的 if 作为第二个代码 - 没有区别。这只是什么代码看起来更清晰的问题。

For the first example, if pieceisnotonedge returns false, will it also check the next condition?

没有。它将“short-circuit”,因为如果第一个条件为假,则不需要检查后面的条件。阅读更多 here and here.

这是由 C++ standard 保证的:

7.6.14

... && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

请注意,对于||,这是相反的,即如果第一个条件为“真”,则不需要检查后面的条件

Shall i use; or...

两者都是一样的,如果你有一个简短的 if 语句(只有两个条件),我建议使用第一种方法。在效率方面没有区别,您可以通过在 godbolt

上查看两种情况下生成的程序集来验证这一点

For the first example, if pieceisnotonedge returns false, will it also check the next condition?

不,不会。因为 build-in logical operatorsshort-circuiting。来自 cppreference.com:

Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like a regular function calls and always evaluate both operands

因此,在

if (pieceisnotonedge && board[row+1][col] == 0)

如果 pieceisnotonedgefalse,则不会计算第二个。因此,嵌套 ifs 是多余的,您可以使用第一个版本。

对于显示的代码没有区别,只有当 pieceisnotonedgetrue 时才会评估两个 board[row+1][col] == 0

如果你应该使用一个或另一个,不能说是笼统的,因为它也取决于其他因素(如语义、可读性等)。

如果你例如如果 pieceisnotonedgeboard[row+1][col] == 0 为假,你想要执行它完成的操作,那么你可能会使用 &&,因为那样你可以写:

if (pieceisnotonedge && board[row+1][col] == 0) {
} else {
  // do something else
}

用你的其他风格你需要写:

if (pieceisnotonedge){
    if (board[row+1][col] == 0) {
      // do something else
    }
} else {
   // do something else
}

一般来说,您的首要目标应该是拥有可读的代码。虽然 pieceisnotonedge && board[row+1][col] == 0 易于阅读,但更复杂的表达式可能不那么容易。所以你会根据具体情况决定,如果你想使用一个表达式或多个 if.