Taken from Introduction to Ada—If expressions:
Ada's
if
expressions are similar toif
statements. However, there are a few differences that stem from the fact that it is an expression:All branches' expressions must be of the same type
It must be surrounded by parentheses if the surrounding expression does not already contain them
An
else
branch is mandatory unless the expression followingthen
has a Boolean value. In that case an else branch is optional and, if not present, defaults toelse True
.
I do not understand the need to have two different ways of constructing code with the if
keyword. What is the reasoning behind this?
Also there case
expressions and case
statements. Why is this?
I think this is best answered by quoting the Ada 2012 Rationale Chapter 3.1:
One of the key areas identified by the WG9 guidance document [1] as needing attention was improving the ability to write and enforce contracts. These were discussed in detail in the previous chapter. When defining the new aspects for preconditions, postconditions, type invariants and subtype predicates it became clear that without more flexible forms of expressions, many functions would need to be introduced because in all cases the aspect was given by an expression. However, declaring a function and thus giving the detail of the condition, invariant or predicate in the function body makes the detail of the contract rather remote for the human reader. Information hiding is usually a good thing but in this case, it just introduces obscurity. Four forms are introduced, namely, if expressions, case expressions, quantified expressions and expression functions. Together they give Ada some of the flexible feel of a functional language.
In addition, if
statements and case
statements often assigns different values to the same variable in all branches, and nothing else:
if Foo > 10 then
Bar := 1;
else
Bar := 2;
end if;
In this case, an if
expression may increase readability and more clearly state in the code what's going on:
Bar := (if Foo > 10 then 1 else 2);
We can now see that there's no longer a need for the maintainer of the code to read a whole if
statement in order to see that only a single variable is updated.
Same goes for case
expressions, which can also reduce the need for nesting if
expressions.
Also, I can throw the question back to you: Why does C-based languages have the ternary operator ?:
in addition to if statements?
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