Search

7.1 — Control flow introduction

When a program is run, the CPU begins execution at the top of main(), executes some number of statements (in sequential order by default), and then the program terminates at the end of main(). The specific sequence of statements that the CPU executes is called the program’s execution path (or path, for short).

Consider the following program:

The execution path of this program includes lines 5, 7, 8, 10, and 12, in that order. This is an example of a straight-line program. Straight-line programs take the same path (execute the same statements in the same order) every time they are run.

However, often this is not what we desire. For example, if we ask the user for input, and the user enters something invalid, ideally we’d like to ask the user to make another choice. This is not possible in a straight-line program. In fact, the user may repeatedly enter invalid input, so the number of times we might need to ask them to make another selection isn’t knowable until runtime.

Fortunately, C++ provides a number of different control flow statements (also called flow control statements), which are statements that allow the programmer to change the normal path of execution through the program. You’ve already seen an example of this with if statements (introduced in lesson 4.10 -- Introduction to if statements) that let us execute a statement only if a conditional expression is true.

When a control flow statement causes point of execution to change to a non-sequential statement, this is called branching.

Categories of flow control statements

Category Meaning Implementated in C++ by
Conditional statements Conditional statements cause a sequence of code to execute only if some condition is met. If, switch
Jumps Jumps tell the CPU to start executing the statements at some other location. Goto
Function calls Function calls are jumps to some other location, and then back to the starting point. Function calls
Loops Loops tell the program to repeatedly execute some sequence of code zero or more times, until some condition is met. While, do-while, for, ranged-for
Halts Halts tell the program to quit running. std::exit(), std::abort()
Exceptions Exceptions are a special kind of flow control structure designed for error handling. try, throw, catch

We’ll cover all of these categories in detail throughout this chapter, with the exception of exceptions (ha) which we’ll devote an entire future chapter to (chapter 20).

Prior to this chapter, the number of things you could have a program do was fairly limited. Being able to control the flow of your program (particularly using loops) makes any number of interesting things possible! No longer will you be restricted to toy programs and academic exercises -- you will be able to write programs that have real utility.

This is where the real fun begins. So let’s get to it!


7.2 -- If statements and blocks
Index
6.x -- Chapter 6 summary and quiz

52 comments to 7.1 — Control flow introduction

  • nav

  • mqu

    "Don’t use it as an easy way out, you’ll leak resources."

    Isn't it a responsibility of OS to clean up after the process that have been terminated?

    • nascardriver

      The OS may or may not clean up the mess you left behind. Most modern OS do clean up, but it's bad practice to rely on this. You might also use types that need special cleanup, like writing an "End" message to a log file or saving the game progress. If you terminate your program, the memory of those types will be freed (Assuming modern OS), but they won't be able to perform their special cleanup routine.

  • Constantine

    Is it better to use

    instead of exit(0)?

    • nascardriver

      Yes, but it should be avoided altogether. I updated the lesson to use `std::exit` and to discourage its use. Thanks for bringing this to our attention!

  • Nikola

    Hey guys,

    Quick question. Are you sure that including cstdlib is necessary to be able to call exit(0)?
    I just tried compiling this code and forgot to put #inlcude <cstdlib> and the program compiled and ran correctly. I'm using GNU GCC on Ubuntu 18.04. Is this behavior some kind of GCC extension or something else?

    Best regards,
    Nikola

    • nascardriver

      Yes, you need <cstdlib>. If you code works without it, you're including a header that itself includes <cstdlib>. It's not guaranteed that your code works with other compilers. If you use something, include its header.

      • Nikola

        Damn... I must be missing something then. Would you be so kind to help me resolve this, nascardriver?

        This is my main.cpp:
        <code>
        #include <iostream>                // Allows usage of the console output and input

        #include "chapter_L_5_1_example_0_version.hpp"

        void cleanup(void)
        {
        }

        // Main program function.
        int main(int argc, char **argv)
        {
            std::cout << "Version: "
                << VERSION_chapter_L_5_1_example_0_MAJOR << "."
                << VERSION_chapter_L_5_1_example_0_MINOR << "."
                << VERSION_chapter_L_5_1_example_0_PATCH << "\n\n";
            
            cleanup();
            
            exit(0);
            
            std::cout << "This will never execute!\n";
            
            // Signal successful program termination.
            return 0;
        }
        </code>

        and finally, this is the chapter_L_5_1_example_0_version.hpp:
        <code>
        #ifndef CHAPTER_L_5_1_EXAMPLE_0_VERSION_HPP
        #define CHAPTER_L_5_1_EXAMPLE_0_VERSION_HPP

        // Version definition for the target_0172
        #define VERSION_chapter_L_5_1_example_0_MAJOR 0
        #define VERSION_chapter_L_5_1_example_0_MINOR 0
        #define VERSION_chapter_L_5_1_example_0_PATCH 0

        #endif // CHAPTER_L_5_1_EXAMPLE_0_VERSION_HPP
        </code>

        This is as simple as it gets... Or at least I think so.

        Thank you for the quick reply, nascardriver.

        P.S.
        Would you mind telling me how to format the code here in the comment section?

        • nascardriver

          Resolve what exactly? Your system's implementation of iostream includes cstdlib somehow. That's not standard behavior, but you can't change it.

          > Would you mind telling me how to format the code here in the comment section?
          Square brackets [], not the triangle ones <>

  • Chase

    "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 tense of "run" seems off. Perhaps you meant "When a program is ran" or "When a program runs".

  • iii

    don't you need a parenthesis after cleanup? compile error occurred

  • in C# exceptions can be caught and handled thus:

    is it similar in C++ or are the try... catch... keywords just in C#

  • Michaek Wycombe

    Oops; exceptions are in Ch14 not Ch15 as referenced in this chapter

  • Eri

    If you had to roughly say, is all the material on this site about a semesters worth at a college or university?

    • nascardriver

      Hi Eri!

      This depends on the country, university, module and requirements to take that module.
      If the module doesn't have any requirements students without any experience in programming should be able to pass it. This means, you'll probably learn C (Basic data types, loops, if, functions) and write a couple of algorithms.
      On person mentioned his university getting all to way to chapter 12, he didn't let me know the country/university unfortunately.
      If you finish all 18 chapters everything that you university could possibly ask you to do should've been covered. You might want to do chapter(s 17 and) 18 early, since those seem likely to be necessary earlier in university.

    • Alex

      My best guess is probably more like a semester and a half.

    • WiseFool

      Not only that, but it cleverly weaves in a quite a few topics that would often be part of a separate Computer Science class instead.  (Great website!!  Thank you so much, Alex!  Keep it up!)

  • rahul

    Good Evening sir,
    I am talking about the inbuilt getpass function(a function of conio.h header file)
    which reads a password from the console

    how to declare this func??

  • rahul

    good evening sir
    I want to ask a question

    sir how can we declare getpass function?

  • Zero Cool

    I think you should change "chapter 15" for "chapter 14" in the following text "We discuss exceptions in chapter 15."

    Keep up with the good work Alex!

  • Zero Cool

    Hi Alex. I have a question for you:
    I know you use Microsoft Visual Studio for compile your examples. But when you do an application do you use the same software? Or do you use just a text editor and compile with the console?

    And do you use Windows, MacOS or Linux for development and why?

    I'm just curious about what is the best software and OS for developers.

    Thanks again for all your work in this website.

    • Brian Gaucher

      Disclaimer: This answer is subjective and based on my own opinion.

      I started out programming on Windows using IDEs (Like PyCharm or IntelliJ), I found that I became dependant on the IDE auto-complete and highlighting too much and didn't fully understand the syntax.

      A little while later, I switched to Linux (I started with dual-boot), I tried Code-Blocks, and I might try again later, I enjoyed it's simplicity, and performance compared to do-it-all IDE. But currently I use the linux terminal for my programming. I use Vim for text-editing, and g++ for compiling. Not having under-line, automatic compiling, and auto-complete forces me to understand the basics more. If you can't get the basics, give up on the advance. IDEs tend make beginners lazy with the basics, then we struggle with the advance. So I suggest use the most simple tools possible (feel free to use a graphical text editor bro), then later, use IDEs in large projects to save time finding small errors.

      • Merlin

        I think you should use the tool, you feel comfortable with. Visual Studio is pretty easy and it's got all what a developer needs at the beginning. But there are many other IDEs which are worth testing as well! :)

  • Weejtoen

    Thank you very much for the nice tutorial. I have been trying to learn C++ for a while now, but never found the right tutorial, untill this website!

  • Hello Hello Alex. Am from Africa in country called Kenya.Am a student and i want to be a programmer and since started learning using this site its much easier to understand C++ and am looking forward to finish learning C++and learn JAVA with your site. God Bless.

  • Jim

    Alex,
    This may not be the proper place to ask this, but suppose I want to pause the program for a while. Lets say 10 to 20 seconds more or less.  Is there a pause function or some way to do this without just using cout << "Press any key to continue";, in C++.

    • Jim

      Alex,
      Continuing from the above. Edit didn't work for some reason. I'm looking for two methods to do this. A function to pause the program waiting for the user to hit any key to continue and another that times out after a given time.

    • Alex

      Prior to C++11, there's no way to do this in standard C++. Different operating systems have OS-specific functionality to do this -- for example, on Windows, windows.h contains function Sleep(), which takes a parameter indicating how many milliseconds to sleep for.

      In C++11, you can do this:

  • papaz

    hey man, thanks for the series, amazing work.
    can you advice on a more detailed exercises we can use?

  • techsavvy....aye

    Typo, in "Loops" for is printed twice.

  • Todd

    I like the fact that you've introduced each of these powerful concepts with a hint to their potential before diving in to the syntax.

    The following independent clause confused me:

    "control jumps to the nearest block of code that has declared it is willing to catch exceptions of that type."

    Is "control jumps" a noun that "is willing to catch exceptions", or is "jumps" being used as a verb (in which case "it is" is confusing and grammatically incorrect). I would recommend rewriting this clause. I can't tell what you're trying to say here.

    • Alex

      I rewrote a few of the sentences to:

      Finally, exceptions offer a mechanism for handling errors that occur in a function. If an error occurs in a function that the function cannot handle, the function can trigger an exception. This causes the CPU to jump to the nearest block of code that handles exceptions of that type.

      Is that clearer?

  • FrostByte

    "Unlike more modern programming languages, such as C# or D, C++ does not provide a foreach keyword."

    This is not true. C++11 provides for-each loops! At least it should be noted there.

    Source: http://en.wikipedia.org/wiki/Foreach_loop#C.2B.2B

  • Can we use break;'s instead of exit?

  • Uri

    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!

  • Jeff

    Alex, what is the difference, if any, between using a "halt":

    As opposed to using a standard "return" type of statement:

    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.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]