History
The first popular use of braces to indicate scope was the
Algol programming language from about 1960.
Many newer languages have chosen better alternatives
to this particularly awkward and error-prone notation.
For example, Visual Basic uses keywords to indicate the
end of statement scope and Python uses indentation,
but the C/C++/Java/C# family continues to use braces.
One-statement body
For if
, while
, and for
statements
the rule is that the body consists of one statement.
If you want more than one statement in the body, you can
enclose the statements in curly braces. Remember that excess
white space, blanks, tabs, and newlines, don't
change the interpretation of a program's syntax.
For example,
if (x==1) n++;
is the same as
if (x==1)
x++;
is the same as
if (x==1) {
x++;
}
as are many other variations. The braces are necessary when
there is more than one statement in the body.
if (x==1) {
n++;
p++;
}
This will increment both n
and p
if x
is one.
In contrast,
if (x==1)
n++;
p++;
will increment only n
if x
is one, then always
increment p
, despite the misleading indentation.
What is "one" statement?
In addition to the obvious single statements, eg an assignment statement,
an if
, while
, or other statement that may contain
a body is one statement.
while (cin >> x)
if (x==1)
n++;
else
n--;
The if
statement counts as only one statement, even tho
it contains other statements.
Rule: Always indent
Regardless of the use of braces, always indent statements that are
in the body of another statement.
Common rule: Always use braces
Altho the language doesn't require it, some programming style standards
require the use of the braces, even if there is only one statement in the
body of another statement. Why? (1) Because it improves the uniformity and
therefore readability, and (2) because inserting an additional statement in
the body where there is only one statement is less error-prone because it's
easy to forget to add braces when the indentation gives such a strong (but possibly misleading)
guide to the structure.