Delphi 'AND' 评估有 2 个条件

标签 delphi

我不得不选择 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 中描述这种行为的地方吗?

最佳答案

documentation link is here :

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 中测试 FalseTrue。始终编​​写这样的代码:

if not somefunc() and anotherfunc() then 

关于Delphi 'AND' 评估有 2 个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15084323/

相关文章:

Delphi 布局管理器/表单生成器开源吗?

windows - 为什么自定义光标图像显示不正确?

delphi 变量值在循环中的线程中发生变化

string - 如何通过模糊匹配查找字符串中子字符串的位置

vb.net - Delphi 中的 VB [(Function) 句柄 ...] 等效项

delphi - Delphi XE2 中的 XML 数据绑定(bind)向导到哪里去了?

delphi - 我需要知道一种方法来确定文件是以独占模式还是以其他方式(读写等)打开?

database - Delphi - 网络 ODBC 数据库 (MS Access)

Delphi接口(interface)继承: Why can't I access ancestor interface's members?

Delphi - 将 NtCreateKey 与 HKCU 结合使用