Statements vs Expressions
- A statement is something that does something.
- An expression is something that evaluates to something.
if (done) exit();
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.
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");