Statements and the Use of Semicolons


Statements and the Use of Semicolons


In C/C++, a statement is a complete instruction that tells the computer what to do. The termination of a statement with a semicolon is a syntactic requirement of the language (this is in contrast to several other computer languages where the end of a line indicates the termination of a statement). The omission of a semicolon from a statement is a “bug” that will often prevent a sketch from compiling. If you attempt to compile a sketch in which a statement lacks its semicolon, you are likely to obtain several rather confusing error messages.

Statements can span multiple lines, so not every line will necessarily ends with a semicolon. For example, the following statement spans two lines (even though, in this case, it is short enough that it could have easily been written on one line):

                    x = 32 * a +
                        17 * b;

Conversely, although it is not considered good programming style, a single line can contain multiple statements. For example, the following contains three assignment statements (where variables are set to particular values):

                    x = 42; y = 24; z = 10;

Nevertheless, the vast majority of sketches are written with one (and only one) complete statement per line, thus most lines of code are written with a single semicolon that terminates the line. (However, an inline comment may follow the statement, and in that case, the semicolon wouldn't truly terminate the complete line.)

As something of an aside, blocks of code are one or more statements collected together in braces (“{” and “}”). One does not place a semicolon after the closing brace (although if you do put one there, it causes no harm). Without considering the details here, we will merely say that one must use blocks when grouping statements together as a collective entity, such as the statements that constitute the “body” of a function.

Important points:

  • Statements are complete instructions.
  • A single statement can span multiple lines.
  • Multiple statements can appear on a single line.
  • All statements must be terminated with a semicolon.

  • Other product and company names mentioned herein are trademarks or trade names of their respective companies. © 2014 Digilent Inc. All rights reserved.