I'm learning Ada by fixing bugs and reading code. I've noticed some if statements that are ganged with "and" and others with "and then". similarly, there is "or" and other places there is "or else". A co-worker says it's just syntactic sugar and makes no difference. I wonder if he's right?
-
5NWS - a shorter (and correct) answer is No! – Simon Wright Jun 10 '13 at 16:47
-
2There is semantic difference as expressions in "and then" and "or else" are lazily evaluated. – darkestkhan Jun 12 '13 at 11:53
-
Your colleague's evaluation was rather lazy. – TamaMcGlinn Nov 09 '21 at 08:13
4 Answers
In Ada and then
and or else
are so-called 'short-circuit' forms of, correspondingly, and
and or
operators:
Shortcut operators [
and then
,or else
] are used to make the evaluation of parts of boolean expressions conditional. This should never be done to speed up the evaluation (with modern optimizing compilers, it will possibly not have that effect). The correct use is to prevent the evaluation of expressions known to raise an exception.
Example (taken, as the explanation above, from wikibooks/Ada):
if Dog /= null and then G (Dog) then
Walk (Dog);
end if;
Here G (Dog) will be evaluated only if Dog is not null. Without and then
it would be evaluated anyway, raising an exception if Dog is null indeed.
Note that and then
and or else
are, strictly speaking, not operators, as they cannot be overloaded.
I'd suggest reading this wikibook, it'll greatly help you in your journey through Ada. )

- 103,633
- 15
- 192
- 229
Suppose FuncB is a function returning Boolean that has a side effect. In
if False and FuncB then
null;
end if;
the side effect of FuncB occurs, while with the short circuit form
if False and then FuncB then
null;
end if;
the side effect of FuncB does not occur.

- 53
- 5
The and then
construct is a characteristic that some programming languages use called short circuit.
You can test and understand this functionality by trying these code snippets:
x:=0;
if false and 1/x=1 then
null;
end if;
This one will result in a divide by zero exception.
x:=0;
if false and then 1/x=0 then
null;
end if;
This one will not raise an exception, because it doesn't check the second condition.

- 254,901
- 44
- 429
- 631

- 130
- 3
-
`false and [then] 1/x` will give you a compile-time error message, since `1/x` isn't of type `Boolean`. – Keith Thompson Jun 26 '13 at 00:14
if (i=0) AndAlso (Func()) then
- use this if you're trying for short circuit in VBScript
-
As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 07 '21 at 08:15