Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a Boolean expression (with side effects) not enough as a statement?

function A: Boolean;
function B: Boolean;

I (accidently) wrote this:

A or B;

Instead of that:

if not A then
  B;

The compiler rejects the first form, I am curious why?

With short circuit evaluation they would both do the same thing, would they not?

Clarification: I was wondering why the language was not designed to allow my expression as a statement.

like image 957
Jens Mühlenhoff Avatar asked Apr 02 '14 13:04

Jens Mühlenhoff


2 Answers

The first is an expression. Expressions are evaluated. Expressions have no visible side effects (like read or write a variable). Both operands of the expression are functions and those can have side effects, but in order to have side effects, a statement must be executed.

The second is a statement. It compares the result of an expression and based on the evaluation calls another function.

The confusing part, is that in this case, Delphi allows us to disregard the result of a function and execute it as a function. So you expect the same for A or B. But that is not allowed. Which is great because the behaviour is ambiguous. For example, if yo have lazy evaluation enabled. And A evaluates to true, is B called yes or no.

like image 70
Toon Krijthe Avatar answered Nov 16 '22 03:11

Toon Krijthe


Simply, because the compiler is expecting a statement and the expression that you have provided is not a statement.

Consult the documentation and you will find a list of valid statements. Your expression cannot be found in that list.

You asked in the (now deleted) comments why the language designers elected not to make such an expression count as a statement. But that question implies purpose where there may have been none. It's perfectly plausible that the designers did not decide not to do this. Rather they never considering doing it in the first place. Languages are generally designed to solve specific problems. It's perfectly plausible that the designers simply never considered treating such expressions as statements.

like image 44
David Heffernan Avatar answered Nov 16 '22 02:11

David Heffernan