The definition of an expression and a statement โ and even if it exists as one or the other โ refers to a particular language and grammar that describes it.
Well, let go:
An operator is some โevaluation codeโ 1 which is not displayed in the context of the expression; and
An expression is code that appears in a context where the resulting value can be used by substituting the expression.
{Very weak "definition", but no single language. Although some languages โโare strict when side effects may not happen โ and code that runs without a result or side effect is useless โ I donโt think that discussing this is fundamental to the differences.}
For example, let's look at printf in C. This is a function, on the other hand, is a side effect and returns a value ; usually the return value is ignored. This way printf can appear as a statement
printf("Hello world!");
and expression
if (8 == printf("Hello %s!", name)) {
(A function call with a void return type can only appear in the context of an operator in C, but this is imposed by the type system, not the parser.)
Similarly, take these two lines in JavaScript x = 1; and x = (y = 2); . x = .. is the operator, and y = 2 is the expression that gave the value.
In both of these examples, we see that this is a product of grammar, defined if it is considered as an expression or expression.
Unlike Ruby, it can consider a top-level assignment as an expression:
[1].map {|x| x = 2}
Now let's take the Python peak (2.x). In this case, print is a statement, so they work and do not work accordingly:
print "Look ma, no parenthesis!" x = lambda y: print "Whoops!"
What about if constructs are these expressions or expressions? Again, this depends on the specific language. In C and Java, such expressions are explicit statements: there is no way to use, for example, to replace a value.
On the other hand, Scala (and Ruby) allows you to use such flow control constructs as expressions, although they can also be displayed as operators:
var emotionalResponse = if (color == "green") { log.cheer() new Cheering() } else { new Tears() }
Phew This is a lot - and it is not very complete. But back to the "definition", which can be recounted as such, taking into account the following examples:
If the construction in question can occur where a value is required (for example, on the right side of an assignment, as an argument of a function, as an input to another expression), then this can be considered as an expression; and most definitely is an expression when in such a context. If a construct appears in a place where it is impossible to access through the substitution, then it (or, rather, can act as) an operator.
1 Another class of derived conditions is a declaration, such as function declarations in C definitions or classes in Java, and may not be statements; as the following is fragmented in the same way as most of the note.