Skip to main content
Engineering LibreTexts

12.4: Compound Statement

  • Page ID
    10313
  • The Need for a Compound Statement

    For illustration we will use the syntax for the if then else control structure within the C++ programming language. However this problem generally exists for all control structures within any language that requires the use of compound statements. The syntax is:

    if (expression)
      statement;
    else
      statement;
    

    Within the C++ programming language there can be only one statement listed as the action part of a control structure. Often, we will want to do more than one statement. This problem is overcome by creating 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;
      }
    

    Because programmers often forget that they can have only one statement listed as the action part of a control structure; the C++ programming industry encourages the use of indentation (to see the action parts clearly) and the use of compound statements (braces), even if there is only one action. Thus:

    if(expression)
      {
      statement;
      }
    else
      {
      statement;
      }
    

    By writing code in this manner, if the programmer modifies the code by adding more statements to either the action true or the action false; they will not introduce either compiler or logic errors. Using indentation and braces should become standard practice for C++ programmers and programmers in any other language that require the use of compound statements with the control structures.

    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 block. 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.