Section 4

Expressions and Statements

Formally speaking, an expression returns a value and produces no side effect. By contrast, a statement is executed for its side effectes and returns no value. Side effects norammly means changing program memory. However, in practice, programming languages do not make a clear distinction between them.

note

Some language constructs have side effects while returning a value. In C, a = 3 updates the memory location of a to be 3, while returning that value 3.

If a programming language do not have side effects, its semnatics could be simple and precise as mathematical expressions. After introducing side effects into a language, the semantics will most likely get complicated and may introduce problems. And that is a main reason why the order of evaluation matters a lot.

Generally speaking, people say evaluating expressions and executing statements because what we get for an expression is its value, and what we get for a statement is a side effect.

Evaluations

Applicative order evaluation (a.k.a. strict evaluation)

All operands are evaluated first and then operators are applied to them. This corresponds to a bottom-up evaluation of the parse tree.

note

However, if multiple operands exist, the order of evaluation is not defined in some languages. If there is no side effects, the order won't matter that much. However, if there is side effect involved, different order may lead to different output.

Delayed evaluation (a.k.a. nonstrict evaluation)

Operands are not evaluated until it is used when evaluating the operator application.

Short circuit evaluation

In a programning language, the designer can specify such rule that boolean expressions are evaluated from left-to-right, and whenever the whole expression's value is known, we stop evaluating the rest of it. This is a special case of nonstrict evaluation.

if (true or isTrue(b)) then do_something() end. Here, isTrue(b) may or may not be evaluated depends on whether the language has a short circuit evaluation rule in its semantic definition.

note

For a better image of different evaluation strategies, see http://en.wikipedia.org/wiki/Evaluation_strategy

Examples

{"Not": [
    {"And": ["True", "False"]}
]}
{"Print": [
    {"Not": [
        {"And": ["True", "False"]}
    ]},
    "End"
]}
{"Assign": [
    "x",
    {"Not": [
        {"And": ["True", "False"]}
    ]},
    {"Repeat": [
        {"Print": ["x"]},
        "End"
    ]}
]}