📄 5.8.2_3.htm
字号:
<html>
<head>
<title>编译原理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link type="text/css" rel="stylesheet" href="../css/specification.css">
</head>
<body>
<table align=right width=300>
<tr>
<td><img src="../images/previous.gif" onmouseover="javascript:style.cursor='hand'" onclick="vbscript:window.location.href='5.8.2_2b.htm'"></td>
<td><img src="../images/next.gif" onmouseover="javascript:style.cursor='hand'" onclick="vbscript:window.location.href='5.9.0.htm'"></img></td>
</tr>
</table>
<br><br>
<font class="title2"><b>5.8.2.3 类型转换</b></font>
<table><tr><td>    </td>
<td class="content">
<p>
考虑表达式s+i,其中x是实型,i是整形。因为在计算机中实数和整数有不同的表示,并且对整数和实数运算使用不同的机器指令,编译器首先对x和i进行类型检查,在生成中间表示时插入一些转换操作,把运算变成一对实数上的运算。例如,x+i的后缀式可能是
</p>
</td></tr></table>
<table><tr><td>    </td>
<td class="content">
<P>
x i inttoreal real+
</p>
</td></tr></table>
<table><tr><td>    </td>
<td class="content">
<P>
这里,inttoreal算符把i从整数转换成实数,然后,完成实数加运算。 语言定义出必须做什么样的类型转换。例如,当整数赋给实型变量时,应该把赋值号右边的对象转换成左边对象的类型。
</p>
</td></tr></table>
<table><tr><td>    </td>
<td class="content">
<P>
<b>例5.28</b> 考虑把算术算符op作用于常数和标识符形成的表达式,假设运算对象有整型和实型两个类型,函数lookup(e)返回符号表中保存在e条目中的类型。图5.35给出其翻译模式,因为语义动作不生成中间代码,所以,看不到从整数到实数的转换。<br><br>
</p>
</td></tr></table>
<table><tr><td></td>
<td class="content">
<P>
E→num {E.type:=integer;} <br>
E→num.num {E.type:=real;} <br>
E→id {E.type:=lookup(id.entry)} <br>
E→E<sub>1</sub> op
E<sub>2</sub> <br>
{E.type:=IF (E<sub>1</sub>.type=integer)AND(E<sub>2</sub>.type=integer) <br>
THEN integer <br>
ELSE
IF (E<sub>1</sub>.type=integer)AND(E<sub>2</sub>.type=real) <br>
THEN real <br> ELSE IF (E<sub>1</sub>.type=real)AND(E<sub>2</sub>.type=integer) <br> THEN real <br>
ELSE IF (E<sub>1</sub>.type=real)AND(E<sub>2</sub>.type=real) <br>
THEN real <br> ELSE type_error} <br><p>
<b>图5.35</b> 需要类型转换的类型检查<br><br>
</p>
</td></tr></table>
<br>
<table align=right width=300>
<tr>
<td><img src="../images/previous.gif" onmouseover="javascript:style.cursor='hand'" onclick="vbscript:window.location.href='5.8.2_2b.htm'"></img></td>
<td><img src="../images/next.gif" onmouseover="javascript:style.cursor='hand'" onclick="vbscript:window.location.href='5.9.0.htm'"></img></td>
</tr>
</table>
</BODY>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -