Control Statements in C++

Controlling the Flow of Program Execution

Chinese Female Programmer
Christian Petersen-Clausen/Getty Images

Programs consist of sections or blocks of instructions that sit idle until they are needed. When needed, the program moves to the appropriate section to accomplish a task. While one section of code is busy, the other sections are inactive. Control statements are how programmers indicate which sections of code to use at specific times.

Control statements are elements in the source code that control the flow of program execution. They include blocks using { and } brackets, loops using for, while and do while, and decision-making using if and switch. There's also goto. There are two types of control statements: conditional and unconditional.

Conditional Statements in C++

At times, a program needs to execute depending on a particular condition. Conditional statements are executed when one or more conditions are satisfied. The most common of these conditional statements is the if statement, which takes the form:

if (condition)

{
    statement(s);
}

This statement executes whenever the condition is true.

C++ uses many other conditional statements including:

  • if-else: An if-else statement operates on an either/or basis. One statement is executed if the condition is true; another is executed if the condition is false.
  • if-else if-else: This statement chooses one of the statements available depending on the condition. If no conditions are true, the else statement at the end is executed.
  • while: While repeats a statement as long as a given statement is true.
  • do while: A do while statement is similar to a while statement with the addition that the condition is checked at the end.
  • for: A for statement repeats a statement as long as the condition is satisfied.

Unconditional Control Statements

Unconditional control statements do not need to satisfy any condition. They immediately move control from one part of the program to another part. Unconditional statements in C++ include:

  • goto: A goto statement directs control to another part of the program.
  • break: A break statement terminates a loop (a repeated structure) 
  • continue: A continue statement is used in loops to repeat the loop for the next value by transferring control back to the beginning of the loop and ignoring the statements that come after it.
Format
mla apa chicago
Your Citation
Bolton, David. "Control Statements in C++." ThoughtCo, Aug. 27, 2020, thoughtco.com/definition-of-control-statements-958050. Bolton, David. (2020, August 27). Control Statements in C++. Retrieved from https://www.thoughtco.com/definition-of-control-statements-958050 Bolton, David. "Control Statements in C++." ThoughtCo. https://www.thoughtco.com/definition-of-control-statements-958050 (accessed March 28, 2024).