布尔表达式的作用p181 ■布尔表达式的作用 ◆计算逻辑值 ◆控制流语句如if-then,if-then-else和while-do 等之中的条件表达式 ■例如 ◆1or(not0and0)or0 ◆a<borc<d and e<f if a<b or c<d and e<f then x:=1 else x:=-1 ◆while a<bdoa:=a-b 2025/4/3 节目录 ☒D☑6
2025/4/3 6 布尔表达式的作用 p181 布尔表达式的作用 计算逻辑值 控制流语句如if-then,if-then-else和while-do 等之中的条件表达式 例如 1 or ( not 0 and 0 ) or 0 a<b or c<d and e<f if a<b or c<d and e<f then x:=1 else x:=-1 while a<b do a:=a-b 节目录
布尔表达式的文法p181 ■布尔表达式-一用布尔运算符号(and,or,not) 作用到布尔变量或关系表达式上而组成 ◆例如布尔表达式:a or b and c〈d ■考虑如下生成布尔表达式的文法 ◆E→EorE|E and Enot E|(E)|id relop id id 其中relop:表示六个关系运算符之一 例如E=>EorE ==>E or E and E ==>E or E and id relop id 对应语法树 ==>E or id and id relop id ==>id or id and id relop id a b d 2025/4/3 节目录☑回7
2025/4/3 7 布尔表达式的文法 p181 布尔表达式——用布尔运算符号(and,or,not) 作用到布尔变量或关系表达式上而组成 例如 布尔表达式: a or b and c < d 考虑如下生成布尔表达式的文法 E→E or E|E and E|not E|(E)|id relop id|id 其中relop表示六个关系运算符之一 例如 E==>E or E a b c < d 对应语法树 ==>E or E and E ==>E or E and id relop id ==>E or id and id relop id ==>id or id and id relop id 节目录
数值表示法p182 若用1表示真,0表示假,则布尔表达式可以象算术 表达式一样来计算 ■例如逻辑表达式 ■例如关系表达式a<b a or b and not c 可等价地写成: 翻译成三地址代码: if a<b then 1 else 0 (1)T1:=not c 翻译成三地址代码: (2)T2:=b and Ti nextstat100 if a<b goto 103 101T1:=0 xtstat+3 (3)T3:=a or T2 -102goto104 a<b为假 103T1:=1 nextstat+2 104·。 a<b为真> 后续代码 2025/4/13 ☒☑8
2025/4/3 8 数值表示法 p182 若用1表示真,0表示假,则布尔表达式可以象算术 表达式一样来计算 例如 关系表达式 a<b 可等价地写成: if a<b then 1 else 0 翻译成三地址代码: 100 if a<b goto 103 101 T1:=0 102 goto 104 103 T1:=1 104 例如 逻辑表达式 a or b and not c 翻译成三地址代码: (1)T1:=not c (2)T2:=b and T1 (3)T3:=a or T2 nextstat+3 a<b为假 nextstat+2 a<b为真 后续代码 nextstat
布尔式数值计算翻译模式中 有关属性和函数p182 ■属性 ◆E.place综合属性,表示存放布尔表达式值的 名字 ◆relop.op综合属性,表示六个关系运算符之一 ■三地址代码的编号 ◆nextstat给出输出三地址代码序列中下一条代 码的编号(地址索引) ■函数 ◆emit将产生的三地址代码送到输出文件中,每 产生一条三地址代码后,emit便把nextstat:增1 2025/4/3
2025/4/3 9 布尔式数值计算翻译模式中 有关属性和函数 p182 属性 E.place 综合属性,表示存放布尔表达式值的 名字 relop.op 综合属性,表示六个关系运算符之一 三地址代码的编号 nextstat 给出输出三地址代码序列中下一条代 码的编号(地址索引) 函数 emit 将产生的三地址代码送到输出文件中,每 产生一条三地址代码后,emit便把nextstat增1
计算布尔表达式值三地址代码的翻译模式p182 E→E1orE2 [E.place:=newtemp; subl emit(E.place‘:=’E1.place‘or’E2.place)} E→E1andE2 [E.place:=newtemp; sub2 emit(E.place‘:=’E1.place‘and'E2.place)} E→notE1 {E.place newtemp; sub3 emit(E.place‘:=’‘not’El.place))} E→(E1) E.place:=E1.place)} sub4 E→id1 [E.place:=newtemp; relop id2 emit(‘if’idl.place relop.opid2.place sub5 ‘goto'nextstat-+3); emit(E.place‘:=’‘0'); emit 'goto'nextstat+2); emit(E.place‘:=’‘1’)} E→id {E.place:=id.place(与教材不同) sub6 2025/4/3 ☒D1o
2025/4/3 10 计算布尔表达式值三地址代码的翻译模式 p182 E→E1 or E2 {E.place:=newtemp; sub1 emit(E.place‘:=’E1.place‘or’E2.place)} E→E1 and E2 {E.place:=newtemp; sub2 emit(E.place‘:=’E1.place‘and’E2.place)} E→not E1 {E.place = newtemp; sub3 emit(E.place‘:=’‘not’E1.place)} E→(E1) {E.place:=E1.place)} sub4 E→id1 {E.place:=newtemp; relop id2 emit(‘if’id1.place relop.op id2.place sub5 ‘goto’nextstat+3); emit(E.place‘:=’‘0’); emit(‘goto’nextstat+2); emit(E.place‘:=’‘1’)} E→id {E.place:=id.place } (与教材不同) sub6