The 文档链接在这里 https://docwiki.embarcadero.com/RADStudio/en/Boolean_short-circuit_evaluation_(Delphi_compiler_directive):
布尔短路评估
Type |
Switch |
Syntax |
{$B+} or {$B-} {$BOOLEVAL ON} or {$BOOLEVAL OFF} |
Default |
{$B-} {$BOOLEVAL OFF} |
Scope |
Local |
$B 指令在 Delphi 代码生成的两种不同模型之间切换and and or布尔运算符。
在 {$B+} 状态下,编译器生成用于完整布尔表达式求值的代码。
这意味着即使整个表达式的结果已知,也保证对由 and 和 or 运算符构建的布尔表达式的每个操作数进行求值。
在 {$B-} 状态下,编译器生成短路布尔表达式求值的代码,这意味着一旦整个表达式的结果按照从左到右的求值顺序变得明显,求值就会停止。
如您所见,默认选项用于短路评估。
不幸的是,你的测试有点混乱。事实上,您的 Delphi 代码与 C 代码有很大不同。
if (somefunc() == FALSE && anotherfunc() == TRUE) // C code
if (somefunc() = False and anotherfunc() = True) then // Delphi code
在德尔福and
运营商有一个更高的优先级 https://docwiki.embarcadero.com/RADStudio/en/Expressions_%28Delphi%29#Operator_Precedence比等于运算符=
。这意味着您的 Delphi 代码相当于:
if (somefunc() = (True and anotherfunc()) = True) then
但在 C 和 C++ 中,优先级是相反的。所以&&
has 较低优先级 https://en.cppreference.com/w/cpp/language/operator_precedence than ==
。因此,无论短路评估如何,您问题中的 Delphi 和 C++ if 语句在逻辑上是不同的。
我很确定您确实打算像这样编写 Delphi 代码:
if ((somefunc() = False) and (anotherfunc() = True)) then
这将提供与 C++ 代码相同的逻辑,并且您会因短路评估而看到相同的行为。
最后,你不应该测试False
and True
在德尔福。始终像这样编写代码:
if not somefunc() and anotherfunc() then