What is the difference between a statement and an expression?

Asked

Viewed 1,374 times

14

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

1 answer

13


Statement

Statement to statement is usually an imperative way of saying what the code should do. Roughly it’s a command. It generates a "execution".

The word in English does not quite indicate what it is. Declaration is an ambiguous word and may be something else. It may be just a statement of variables, which is usually a statement, but not always.

Then declare a variable, assign value to it, say that it should make a decision, that it should deviate from the normal flow and possibly repeat, even a code block can be considered a statement in various languages.

Expressions

An expression is a code portion 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 the language interprets according to certain rules and creates a result (a "calculation" is made) that is a new value. The process that calculates this value is called "appraisal".

Some languages specify that some commands generate some result and can therefore be used in expressions. In this case what is usually known as statement becomes an expression. So 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 that statements and assignments of variables are expressions, thus not only changing their value, this value is already a result and can be used in an expression.

A statement can contain expressions, but expressions cannot contain declarations. The moment a statement is allowed within 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 with nothing else, obviously the result will be discarded.

Difference

"Statements" produce actions, but not results, as with expressions, therefore cannot be used as part of expressions that require values.

Another common secondary point is that expressions do not usually have side effect, that is, they do not change states, but there is no definition that this is prohibited in expressions. Statements can change states, although not every kind of statement needs to do that, this may be a little different in some languages.

  • 1

    Now it’s clear. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.