What is the difference between a statement and an expression?

9

In the programming world these are two terms that are widely used, but sometimes I see people using them (sometimes even experienced professionals) as if they are interchangeable. Is this valid? When does each term apply?

    
asked by anonymous 27.11.2016 / 23:21

1 answer

8

Statement

Statement in the sense of statement is often an imperative way of saying what the code should do. Roughly it's a command. It generates a " execution ".

The Portuguese word does not indicate well what it is. Statement is an ambiguous word and can be something else. It may be just a statement of variables, which is usually a statement , but not always.

So declare a variable, assign value to it, say it must make a decision, which should deflect normal flow and possibly repeat, even a block of code can be considered a statement in several languages.

Expressions

An expression is a portion of code that generates a value. It is usually composed of other expressions called subexpressions. It is the combination of one or more values, constants, variables, operators, and functions that language interprets according to certain rules and creates a result (a "calculation" is done) which is a new value. The process that calculates this value is called " evaluation ".

Some languages specify that some commands generate some result and therefore can be used in expressions. In this case what is commonly known as statement becomes an expression. Then a if can generate a result:

x = if a > 0 then 5 else 0 //x valerá 5 ou 0

It is more or less common for languages to consider statements and variable assignments as expressions, besides changing their value, this value is already a result and can be used in an expression.

A declaration can contain expressions, but expressions can not contain declarations. The moment a statement becomes allowed inside an expression it becomes an expression.

Most languages allow expressions to be used as statements. For example, calling a function is an expression, and it can be called directly without anything else, obviously the result will be discarded.

Difference

"Declarations" produce actions, but not results, as with expressions , so they can not be used as part of expressions that require values.

Another common secondary point is that expressions do not usually have side effects, that is, they do not change states, but there is no definition that this is forbidden in expressions. Statements can change states, although not all statements need to do so.

    
27.11.2016 / 23:39