6.5: Compound Statement
( \newcommand{\kernel}{\mathrm{null}\,}\)
The Compound Statement
Often, we will want to have more than a single statement within our if statements. Some texts refer to this as a compound statement. The brace symbols – the opening { and the closing } - are used to create a compound statement. For example:
if(expression) { statement; statement; } else { statement; statement; }
You can indeed use the braces with only a single statement, and many programmers do that just to be consistent with all of their code. Just be aware that some people refer to this as a compound statement. Others simply refer to it as a block of code. Either is correct, you just need to understand the terminology.
Other Uses of a Compound Statement
"A compound statement is a unit of code consisting of zero or more statements. It is also known as a code block or a block of code. The compound statement allows a group of statements to become one single entry. You used a compound statement in your first program when you formed the body of the function main. All C++ functions contain a compound statement known as the function body.
A compound statement consists of an opening brace, optional declarations, definitions, and statements, followed by a closing brace. Although all three are optional, one should be present."1
Definitions
- Compound Statement
- A unit of code consisting of zero or more statements.
- Block
- Another name for a compound statement.
Footnotes
1 Behrouz A. Forouzan and Richard F. Gilberg, Computer Science A Structured Approach using C++ Second Edition (United States of America: Thompson – Brooks/Cole, 2004) 100.