When a program is run, the CPU begins execution at the top of main(), executes some number of statements, and then terminates at the end of main(). The sequence of statements that the CPU executes is called the program’s path. Most of the programs you have seen so far have been straight-line programs. Straight-line programs have sequential flow — that is, they take the same path (execute the same statements) every time they are run (even if the user input changes).
However, often this is not what we desire. For example, if we ask the user to make a selection, and the user enters an invalid choice, ideally we’d like to ask the user to make another choice. This is not possible in a straight-line program.
Fortunately, C++ provides control flow statements (also called flow control statements), which allow the programmer to change the CPU’s path through the program. There are quite a few different types of control flow statements, so we will cover them briefly here, and then in more detail throughout the rest of the section.
Halt
The most basic control flow statement is the halt, which tells the program to quit running immediately. In C++, a halt can be accomplished through use of the exit() function that is defined in the cstdlib header. The exit function takes an integer parameter that is returned to the operating system as an exit code, much like the return value of main().
Here is an example of using exit():
#include <cstdlib>
#include <iostream>
int main()
{
using namespace std;
cout << 1;
exit(0); // terminate and return 0 to operating system
// The following statements never execute
cout << 2;
return 0;
}
Jumps
The next most basic flow control statement is the jump. A jump unconditionally causes the CPU to jump to another statement. The goto, break, and continue keywords all cause different types of jumps — we will discuss the difference between these in upcoming sections.
Function calls also cause jump-like behavior. When a function call is executed, the CPU jumps to the top of the function being called. When the called function ends, execution returns to the statement after the function call.
Conditional branches
A conditional branch is a statement that causes the program to change the path of execution based on the value of an expression. The most basic conditional branch is an if statement, which you have seen in previous examples. Consider the following program:
int main()
{
// do A
if (bCondition)
// do B
else
// do C
// do D
}
This program has two possible paths. If bCondition is true, the program will execute A, B, and D. If bCondition is false, the program will execute A, C, and D. As you can see, this program is no longer a straight-line program — it’s path of execution depends on the value of bCondition.
The switch keyword also provides a mechanism for doing conditional branching. We will cover if statements and switch statements in more detail shortly.
Loops
A loop causes the program to repeatedly execute a series of statements until a given condition is false. For example:
int main()
{
// do A
// loop on B
// do C
}
This program might execute as ABC, ABBC, ABBBC, ABBBBC, or even AC. Again, you can see that this program is no longer a straight-line program — it’s path of execution depends on how many times (if any) the looped portion executes.
C++ provides 3 types of loops: while, do while, and for loops. Unlike more modern programming languages, such as C# or D, C++ does not provide a foreach keyword. We will discuss loops at length toward the end of this section.
Exceptions
Finally, exceptions offer a mechanism for handling errors that occur in functions. If an error occurs that the function can not handle, it can raise an exception, and control jumps to the nearest block of code that has declared it is willing to catch exceptions of that type. Exception handling is a fairly advanced feature of C++, and is the only type of control flow statement that we won’t be discussing in this section.
Conclusion
Using program flow statements, you can affect the path the CPU takes through the program and control under what conditions it will terminate. This makes any number of interesting things possible, such as displaying a menu repeatedly until the user makes a valid choice, printing every number between x and y, or determining the factors of a number.
Once you understand program flow, the things you can do with a C++ program really open up. No longer will you be restricted to toy programs and academic exercises — you will be able to write programs that have real applications. So let’s get to it!
5.2 — If statements
|
Index
|
4.7 — Structs
|
5.2 — If statements
Index
4.7 — Structs
Shouldn’t the statement below read that the program will repeatedly execute a series of statements until a given condition is false?
Loops
A loop causes the program to repeatedly execute a series of statements until a given condition is true.
You are correct! I meant to say “while a given condition is true”, but I think it reads even better as “until a given condition is false”. Thanks for noticing!
Alex, what is the difference, if any, between using a “halt”:
if (bIsError1) exit(-1);As opposed to using a standard “return” type of statement:
if (bIsError2) return -1;I’m sure I have written and compiled code before that has multiple return statements, to be executed under various conditions, within the same main(). Is there a reason to favor one type of statement over the other?
UPDATE: I may have partially answered my own question. If exit() is called within a function other than main() does the program terminate outright rather than returning control to main()? Side-effects? Any other reasons to use, or not use, exit()?
exit() will cause the program to terminate immediately, regardless of where it is called.
One thing you’ll need to be careful of when using exit is to make sure you do any necessary cleanup before the program exits. Most of the time, no explicit cleanup is needed. However, it’s probably a good idea to close any open file handles, network sockets, etc… before exiting. Note that destructors to in-scope variables will not be called before the program exits.
[...] 2007 Prev/Next Posts « What Google giveth, Google taketh away… | Home | 5.1 — Control flow introduction » Wednesday, June 20th, 2007 at 6:34 [...]
Hi Alex!!
Just onted to say WOW!!
Your C++ tutorial is AMAZING!!! this clears soooooooo many things for me…very easy to understand – without missing anything!
So thanks alot man!
The more I learn about this language, the more I dislike it. From having to declare functions on top to no foreach loop. Hopefully, it has some other cool features I haven’t learned yet.
Great tutorials Alex!!
would be great though, if you goulc make a pfd version, I’d paypal you some money for it, too…
@prayrit Jain:
c++ has two advantages, the first being its exellent speed and its portabillity on other platforms (mobile ones, mac os, linux…)
replax
Can we use break;’s instead of exit?
break; only breaks a loop in which it is in, while exit() closes the program.
Hi and Hope you are doing well
Is it possible to have a PDF or a document of your lessons in a single file.
If it is, I would be glad to have it.
Just tell me how?
Best Regards
Nima Nouri
PHD Student
Iran
Isfahan University of Technology
Department of Mechanical Engineering
E-mail : nouri.f.nima@gmail.com
Just save all the lessons as html, and use html to PDF and convert them. Sadly there is no ‘official’ PDF file.
[...] the previous lesson on stepping and breakpoints, you learned how to use the debugger to watch the path of execution through your program. However, stepping through a program is only half of what makes the debugger [...]