即使第一个条件为假,是否在if语句中检查所有条件?

时间:2022-06-07 11:03:29

If I have:

如果我有:

bool foo = false; bool bar = true;

bool foo = false; bool bar = true;

If(foo && bar)

如果(foo && bar)

Doea the if-statement check if bar is true or does it skip it because foo already is false?

Doe语句检查bar是否为true或是否跳过它因为foo已经为假?

1 个解决方案

#1


What you are referring to is called short-circuit evaluation, and whether it will happen depends on:

您所指的是短路评估,是否会发生取决于:

  • the language you are programming in
  • 你正在编程的语言

  • in some cases, the implementation (where the language definition neither mandates nor prohibits it)
  • 在某些情况下,实施(语言定义既不强制也不禁止)

  • in some cases, the exact situation (where the language explicitly allows but does not guarantee it, and the implementation may choose whether to short-circuit on a case-by-case basis)
  • 在某些情况下,确切的情况(语言明确允许但不保证,并且实现可以选择是否根据具体情况进行短路)

  • the exact operator you use (some languages provide two ways of writing "and", one "eager" and one "short-circuit"
  • 您使用的确切运算符(某些语言提供两种写“和”的方式,一种“渴望”和一种“短路”

Note that it is not a property of the if statement, which is just taking a single boolean expression which has resulted from you using logical operators; the expression could equally be assigned to a boolean variable, passed as a function parameter, etc.

请注意,它不是if语句的属性,它只是使用一个布尔表达式,这是因为您使用了逻辑运算符;表达式同样可以分配给布尔变量,作为函数参数传递,等等。

#1


What you are referring to is called short-circuit evaluation, and whether it will happen depends on:

您所指的是短路评估,是否会发生取决于:

  • the language you are programming in
  • 你正在编程的语言

  • in some cases, the implementation (where the language definition neither mandates nor prohibits it)
  • 在某些情况下,实施(语言定义既不强制也不禁止)

  • in some cases, the exact situation (where the language explicitly allows but does not guarantee it, and the implementation may choose whether to short-circuit on a case-by-case basis)
  • 在某些情况下,确切的情况(语言明确允许但不保证,并且实现可以选择是否根据具体情况进行短路)

  • the exact operator you use (some languages provide two ways of writing "and", one "eager" and one "short-circuit"
  • 您使用的确切运算符(某些语言提供两种写“和”的方式,一种“渴望”和一种“短路”

Note that it is not a property of the if statement, which is just taking a single boolean expression which has resulted from you using logical operators; the expression could equally be assigned to a boolean variable, passed as a function parameter, etc.

请注意,它不是if语句的属性,它只是使用一个布尔表达式,这是因为您使用了逻辑运算符;表达式同样可以分配给布尔变量,作为函数参数传递,等等。