If语句及if表达式¶
虽然其十分直观的,但我们仍然值得简短介绍一下if
语句以及if
表达式的语法。因为if
表达式解释起来最简单,所以让我们先从它开始介绍。if
表达式有以下形式:
if cexpr then expr1 else expr2;
其中cexpr
是条件表达式(其结果是一个Boolean
值。)。expr1
则是if
表达式在cexpr
结果为true
的取值。相对地,expr2
则是if
表达式在cexpr
结果为false
的取值。
if
语句有如下的一般语法:
if cond1 then
// Statements used if cond1==true
elseif cond2 then
// Statements used if cond1==false and cond2==true
// ...
elseif condn then
// Statements used if all previous conditions are false
// and condn==true
else
// Statements used otherwise
end if;
重要的是要注意,当一个if
语句出现在equation
区域里,无论在if
语句的哪个分支里(对于有elseif
的情况也适用),方程的数量均必须一致。一个例外是在initial equation
或initial algorithm
内的if
乃至不需要else
子句。因为在这些情况下,分支内的方程数量不需要相等。另外一个值得注意的例外是,在函数内使用的if
同样也没有要求方程的数目是在两个分支上相同
Note
请注意,if
语句以及if
表达式内的条件表达式有可能会产生事件。