5.4. Statements and Side-Effects


Statements

A statement performs an action. A statement might change the value of a variable or write something, for example. Unlike an expression, a statement does not have an answer. It just does something.

(In everyday English, a statement is just a sentence that expresses a fact. But in programming languages, that word has a different meaning. A statement in a programming language is really a command.)


Expression-statements

You can convert any expression to a statement by asking for its answer to be ignored. To do that, just write a semicolon after the expresssion. For example,

  2 + 3;
is a statement. It says to compute 2 + 3 and then to ignore the result and move on. Of course, that does not sound like a useful thing to do, and it isn't. (The coding standards require you not to write silly statements like this.)

But some expressions perform actions as well as yielding a value. Those actions are called side-effects. For example, if x is a variable and E is an expression then x = E is an expression; its value is the value of expression E, but it has the side-effect of storing the value of E into x. Making that into a statement yields

  x = E;
which does make sense; it is performed for its side-effect, not for its value.


Performing statements in sequence

If you write statements one after another then they are performed one after another, in the order in which they are written. For example,

  x = 1;
  y = x + 1;
first sets variable x to 1 and then sets variable y to 2.


Compound statements

C++ has several places where you must write just one statement. But you often want to write several statements in sequence. In order to do that, wrap the sequence of statements in left and right braces. That yields a compound statement that is treated like a single statement. For example,

  {
    x = y + 1;
    z = w;
  }
is a compound statement that, when performed, sets x to the value of y+1 and then sets z to the value of w.

A compound statement can contain any number of statements, including none. Statement {} does nothing.


Exercises

  1. Suppose that x is a variable. What does statement

      x + 1;
    
    do? Answer

  2. What is the purpose of a compound statement? Answer

  3. What does it mean for an expression to have a side-effect? Answer