我正在通过修复bug和阅读代码来学习Ada。我注意到有些if语句使用"and"连接,而其他的则使用"and then"。同样地,有一些地方使用了"or",而其他地方则使用了"or else"。我的同事说这只是一种语法糖,并没有什么区别。我想知道他是否正确?
我正在通过修复bug和阅读代码来学习Ada。我注意到有些if语句使用"and"连接,而其他的则使用"and then"。同样地,有一些地方使用了"or",而其他地方则使用了"or else"。我的同事说这只是一种语法糖,并没有什么区别。我想知道他是否正确?
在Ada中,and then
和or else
是所谓的“短路”形式的and
和or
运算符:
短路运算符[
and then
,or else
]用于使布尔表达式的部分条件计算。这永远不应该为了加快计算速度而使用(使用现代优化编译器将可能不起作用)。正确的用法是防止已知会引发异常的表达式的计算。
例如(与上面的解释一样,取自wikibooks / Ada):
if Dog /= null and then G (Dog) then
Walk (Dog);
end if;
if False and FuncB then
null;
end if;
当使用短路形式时,FuncB会产生副作用。
if False and then FuncB then
null;
end if;
FuncB没有产生副作用。
and then
构造是一些编程语言中使用的名为短路的特性。x:=0;
if false and 1/x=1 then
null;
end if;
这个会导致除以零的异常。
x:=0;
if false and then 1/x=0 then
null;
end if;
false and [then] 1/x
会导致编译时错误,因为1/x
不是Boolean
类型。 - Keith Thompson如果 (i=0) AndAlso (Func()) then