当 Pascal 没有布尔类型时,它怎么会有条件?

How can Pascal have conditions when it doesn't have boolean type?

基于正式的Pascal EBNF definition (pg69-75),我看到Pascal只支持3种基本类型:整数、实数和字符串。

在 C 中,任何不同于 0 的值都可以解释为 true 文字。 Pascal 不像 C 那样工作。Pascal 没有布尔类型时如何处理条件表达式?

EBNF 不描述类型系统,它描述语法,而且只描述语法。但是请注意,如果您声明一个变量,它的类型为:

variable-declaration =
identifier-list ":" type .

类型定义为:

type =
simple-type | structured-type | pointer-type | type-identifier .

type-identifier只是identifier可以是boolean,但是EBNF不会告诉你的。您必须查看标准的其余部分。 ISO 7185 定义了 Pascal 的一种方言,相关部分为 6.4.2.2:

The values shall be the enumeration of truth values denoted by the required constant-identifiers false and true...

在 Pascal 中,您最终可能会得到这样的代码:

program BooleanDemo;
var
    myBool : boolean;
    n : integer;
begin
    n := 5;
    myBool := n > 4;
    if myBool then
        writeln('myBool is true')
    else
        writeln('myBool is false')
end.

自己尝试 运行 这段代码,您会发现实际上有一个布尔类型,并且它的工作方式与您预期的完全一样。

Pascal 标准清楚地定义了布尔类型的语法和语义。

从文档中引用您 link 到:

6.4.2.2 Required simple-types

The following types shall exist:

c. Boolean-type. The required type-identifier Boolean shall denote the Boolean-type. The Boolean-type shall be an ordinal-type. The values shall be the enumeration of truth values denoted by the required constant-identifiers false and true, such that false is the predecessor of true. (page 16)

truefalse对应EBNF产生式:

constant = [ sign ] (constant-identifier | number) | string

可产生:

constant = constant-identifier

(因为 [ sign ] 是可选的)

一个constant-identifier只是一个identifier.

还有:

6.7.2.3 Boolean operators

 Boolean-expression = expression .

A Boolean-expression shall be an expression that denotes a value of Boolean-type. (page 49)

Table 6(下页)定义比较运算符的操作数和结果类型(==<=>=<><>in)。在所有情况下,结果类型都是“布尔型”。

最后:

6.8.3.4 If-statements

If the Boolean-expression of the if-statement yields the value true, the statement of the if-statement shall be executed. If the Boolean-expression yields the value false, the statement of the if-statement shall not be executed, and the statement of the else-part, if any, shall be executed. (page 54)