### Compound Statements and Lines of Code

In many many circumstances, it is necessary to arrange two or more statements into a group which can be treated as a single statement. All modern programming languages have some way to do this. The most common way is to enclose the statements in the group in braces { }.

Here is an example:

if (k > 5) {x = 1; y = 2;} else {x = 2; y = 1;}

In this example, the statements x=1; and y = 2; are arranged into one group, and the statements x = 2; and y = 1; are arranged into a second group. Each group qualifies as a statement for the purpose of building an if...then...else structure.

You can see that in C++ (and many other languages including Java and Javascript) a statement ends either in a semicolon (if it is a stand-alone) or in a closing brace (if it is compound).

Another feature of modern programming languages that you should be aware of is that the end of a line of text has no more significance than a space! You can arrange text on lines as you like, and should do so to make it more readable. So the above example can be written equivalently in any of the following ways:

Version A:

if (k > 5)
{
x = 1;
y = 2;
}
else
{
x = 2;
y = 1;
}

Version B:

if (k > 5) {
x = 1;
y = 2;
} else {
x = 2;
y = 1;
}

Versions A and B are both completely equivalent to the original. Clearly there are questions of personal (or corporate) style here.

(For that matter, one could write

if(k>5){x=1;y=2;}else{x=2;y=1;}

but this is not recommended.)

While a compound statement almost always contains two or more statements, it is possible to write a compound statement with only one statement; the only reason for doing so is readability. So for instance, the following two lines are equivalent:

while (j > 0) j = j - 1;

while (j > 0) {j = j - 1;}

It is even possible to write a compound statement with zero statements. It looks like this: {}. I have had a few occassions to do this: when there are many different cases of some situation, and each required a different action, and in a few of the cases, the required action is "do nothing". In that situation, I usually write

{/* Do Nothing! */}

with a comment between the braces to make it clear to the reader that this is an intentional do-nothing statement.

Historically, programming languages have used several different methods to mark the end of a language statement. Take a peek at my short note Separating Statements