3E. Statements

In programming languages, a statement is really a command to do something. For example, C++ statement

  printf("I am happy to meet you.\n");
writes
  I am happy to meet you.
followed by an end-of-line marker. We will see more on printf later.


Turning expressions into statements

In C++, you can make any expression into a statement by writing a semicolon after it. If E is an expression, then statement

  E;
says to evaluate E and to ignore its result. The printf statement above is an example of that; printf("I am happy to meet you.\n"), with no semicolon, is an expression. Its value is the number of characters in the string that printf is asked to write.


Side effects

As you can see from the printf example, evaluating an expression can have side effects. Expression printf("Hello") has value 5, but the process of evaluating it causes Hello to be written out.


Performing statements in sequence

To perform statements one after another, simply write them one after another. For example,

  printf("I am happy to meet you.\n");
  printf("My name is Kim.\n");
writes two lines,
I am happy to meet you.
My name is Kim.

If statements are performed one after the other, indent them both the same amount.


Avoid packing more than one statement on a line

When statements are done in sequence, you normally write them on separate lines. As you become more advanced you will learn of some situations where it makes sense to put more than one statement on a line, as in

  x = 1; y = 0;
That might seem like a way to reduce the line count of your functions. But in this course, don't do that. The standards require that you put separate statements on separate lines. You will need to use more substantative ways to keep functions short.