我不得不选择 Delphi 来完成我最近正在做的一项契约(Contract)工作,我希望有人澄清的一件事是条件语句中的逻辑执行,例如 if
.
我有 C/C++ 背景,在这些语言中,一旦 if
语句已知失败,其余逻辑就不会执行。例如:
if (somefunc() == FALSE && anotherfunc() == TRUE)
在上述情况下,如果 somefunc()
返回 TRUE
,则永远不会调用 anotherfunc()
。
在 Delphi 中,从我目前所见,这并不成立。相反,为了
if (somefunc() = False and anotherfunc() = True) then
然后,无论 somefunc()
返回什么,anotherfunc()
都会被调用。
我读过各种 Delphi 书籍,并重读了一些条件章节,但根本找不到任何提及此行为的地方。谁能指出我在 Delphi 或 Pascal 中描述这种行为的地方吗?
最佳答案
Boolean short-circuit evaluation
Type Switch Syntax {$B+} or {$B-} {$BOOLEVAL ON} or {$BOOLEVAL OFF} Default {$B-} {$BOOLEVAL OFF} Scope Local The $B directive switches between the two different models of Delphi code generation for the and and or Boolean operators.
In the {$B+} state, the compiler generates code for complete Boolean expression evaluation. This means that every operand of a Boolean expression built from the and and or operators is guaranteed to be evaluated, even when the result of the entire expression is already known.
In the {$B-} state, the compiler generates code for short-circuit Boolean expression evaluation, which means that evaluation stops as soon as the result of the entire expression becomes evident in left to right order of evaluation.
如您所见,默认选项用于短路评估。
<小时/>不幸的是,你的测试有点困惑。事实上,您的 Delphi 代码与 C 代码有很大不同。
if (somefunc() == FALSE && anotherfunc() == TRUE) // C code
if (somefunc() = False and anotherfunc() = True) then // Delphi code
在 Delphi 中,and
运算符有一个 higher precedence比等于运算符=
。这意味着您的 Delphi 代码相当于:
if (somefunc() = (True and anotherfunc()) = True) then
但在 C 和 C++ 中,优先级是相反的。所以 &&
有 lower precedence比==
。因此,无论短路评估如何,您问题中的 Delphi 和 C++ if 语句在逻辑上是不同的。
我很确定您确实想像这样编写 Delphi 代码:
if ((somefunc() = False) and (anotherfunc() = True)) then
这将提供与 C++ 代码相同的逻辑,并且您会因短路评估而看到相同的行为。
最后,您永远不应该在 Delphi 中测试 False
和 True
。始终编写这样的代码:
if not somefunc() and anotherfunc() then
关于Delphi 'AND' 评估有 2 个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15084323/