Statements vs Expressions

Statements

Examples:
  • print("Hello World")
  • sleep(1000)
  • return 55
  • if (done) exit();
  • throw SomeError()

In most languages the above type of statements can't be used as expressions. In other words it's typically not permitted to write things like

print("Hello") + sleep(1000)

In some languages all statements are also expressions. In Scala for example functions that does not return anything evaluates to the Unit value. This is however the exception rather than the norm.

Expressions

Examples:
  • "Hello World"
  • 1000
  • 5 + 3
  • errors > 0 ? FAIL : SUCCESS
  • x_flag & mask

You typically can't put an expression where a statement is expected. Most (compiled) languages does not allow for example

print("Hello")
5 + 3             // error: expected statement
print("World")

Both at the same time

Some things can be used both as expressions and statements. A function call that returns a value for example

myFunction()                // As statement
if (myFunction())           // As expression
    print("Returned true!")

In scripting languages it's also common to use short circuiting boolean expressions. In shell scirpting you often see things like

compile_code || exit 1

or in PHP the following is a common pattern

fopen($site,"r") or die("Unable to connect to $site");

Comments

Be the first to comment!