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?
"if/then" lets you test a condition and provide instructions for when the test is true. "if/else" lets you test a condition and provide instructions for when the test is true AND when it is false.
if statement - executes some code if one condition is true. if...else statement - executes some code if a condition is true and another code if that condition is false. if... elseif...else statement - executes different codes for more than two conditions.
Notice that the difference between IF statement and IF-ELSE statement is that there's an additional ELSE attached to it. The IF statement is executed if the statement inside the test condition evaluates to true; otherwise the statements inside the ELSE block is executed.
Main Difference between If-else and Switch CaseThe if-else statement is used to choose between two options, but the switch case statement is used to choose between numerous options. If the condition inside the if block is false, the statement inside the else block is executed.
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. )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With