如果Pascal没有布尔类型,它怎么会有条件?

时间:2017-07-18 15:28:55

标签: grammar pascal ebnf

基于形式Pascal EBNF definition(第69-75页),我看到Pascal只支持3种基本类型:Integer,Real和String。

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

2 个答案:

答案 0 :(得分:8)

Pascal标准明确定义了布尔类型的语法和语义。

从您链接的文件中引用:

  

6.4.2.2必需的简单类型

     

应存在以下类型:

     

...

     

℃。 布尔型。所需的类型标识符布尔值应表示布尔类型。布尔型应为序数型。值应为由所需常量标识符 false true 表示的真值的枚举,以便 false 真即可。   (第16页)

true false 对应于EBNF生产:

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

可以产生:

constant = constant-identifier

(因为[ sign ]是可选的)

constant-identifier只是identifier

此外:

  

6.7.2.3布尔运算符

     

...

 Boolean-expression = expression .
     

Boolean-expression必须是表示Boolean-type值的表达式。   (第49页)

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

最后:

  

6.8.3.4 If-statements

     

如果if语句的Boolean-expression产生值 true ,则应执行if语句的语句。如果Boolean-expression产生值 false ,则不应执行if语句的语句,并且应执行else-part的语句(如果有)。   (第54页)

答案 1 :(得分:4)

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:

  

值应为由所需常数标识符falsetrue表示的真值的枚举...

在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.

尝试自己运行此代码,您会看到实际上有一个布尔类型,它的工作方式与您期望的完全相同。

相关问题