25

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?

erict
  • 1,394
  • 2
  • 14
  • 28

4 Answers4

35

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. )

raina77ow
  • 103,633
  • 15
  • 192
  • 229
4

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.

3

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.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
fabribara
  • 130
  • 3
-1

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