Free eBook - The C++ Workshop

4.3 (3 reviews total)
By Dale Green , Kurt Guntheroth , Shaun Ross Mitchell
  • A new free eBook every day on the latest in tech
  • 30 permanently free eBooks from our core tech library
  1. 1. Your First C++ Application
About this book
C++ is the backbone of many games, GUI-based applications, and operating systems. Learning C++ effectively is more than a matter of simply reading through theory, as the real challenge is understanding the fundamentals in depth and being able to use them in the real world. If you're looking to learn C++ programming efficiently, this Workshop is a comprehensive guide that covers all the core features of C++ and how to apply them. It will help you take the next big step toward writing efficient, reliable C++ programs. The C++ Workshop begins by explaining the basic structure of a C++ application, showing you how to write and run your first program to understand data types, operators, variables and the flow of control structures. You'll also see how to make smarter decisions when it comes to using storage space by declaring dynamic variables during program runtime. Moving ahead, you'll use object-oriented programming (OOP) techniques such as inheritance, polymorphism, and class hierarchies to make your code structure organized and efficient. Finally, you'll use the C++ standard library?s built-in functions and templates to speed up different programming tasks. By the end of this C++ book, you will have the knowledge and skills to confidently tackle your own ambitious projects and advance your career as a C++ developer.
Publication date:
February 2020
Publisher
Packt
Pages
606
ISBN
9781839216626

 

2. Control Flow

Overview

This chapter presents various tools and techniques that are used to control the flow of execution throughout applications. This includes, but is not limited to: if statements, switch statements, and various loops. We will also look at how we control the lifetime of our applications using these techniques, and how they are to be used efficiently. The chapter will end with the creation of a number guessing that that will implement various loops and conditional statements.

 

Introduction

In the first chapter, we covered the absolute essentials of C++ and looked at the key components of a C++ application. We looked at how applications run, how they're built, and how we can get information in and out of them with some basic I/O. Up until this point, the applications we've built have mainly run sequentially; that is, the code we've written has been executed line by line, sequentially. While that's great for demonstration purposes, this generally isn't how real-world applications work.

In order to represent logical systems correctly, we need to be flexible in what we do and when. For example, we may only want to perform a certain action if a given statement is true or to return to an earlier piece of code again. Manipulating execution in this manner is known as control flow (or program flow), and is the topic of this chapter.

To begin with, we are going to look at the humble if statement, one of the most fundamental logic statements...

 

if/else

One of the most basic, yet most important, control flow statements is if. This simple keyword is at the heart of all logic, allowing us to perform a given action only if a specified condition is true. By chaining these if statements together in creative ways, we can model any logical system.

The syntax for an if statement is as follows:

    if (condition) { // do stuff. }

If the statement we use as our condition resolves to true, then the code within the curly braces will be executed. If the statement is false, then it will be skipped. Our condition can be anything that can be either true or false. This can be something simple, such as checking the value of a Boolean, or something more complex, such as the result of another operation or function.

We also have the else statement. This allows code to be executed if, and only if, a preceding if statement's condition evaluates to false. If the condition evaluates to true, however, and the if...

 

switch/case

As we've seen, we can use if/else to perform certain actions based on which conditions are true. This is great when you're evaluating multiple conditional statements to determine flow, such as the following:

    if (checkThisCondition)
    {
        // Do something ...
    }
    else if (checkAnotherCondition)
    {
        // Do something else ...
    }

When we're evaluating the different possibilities of a single variable, however, we have a different statement available to us: the switch statement. This allows us to branch in a similar way to an if/else statement, but each branch is based on a different possible value of a single variable that we're switching on.

A good example of where this would be suitable is the menu application we created...

 

Loops

Alongside if statements, loops are among the most fundamental of programming concepts. Without loops, our code would execute by running through our logic statements one by one and then ending. That's how our applications have worked so far; however, in reality, this really isn't practical. Systems tend to consist of many moving parts, and code execution will jump all around the code base to where it's needed.

We've seen how this can be achieved by creating branches in our code where statements can be evaluated, and we do different things based on the outcome. Another way we do this is via loops. Loops allow us to rerun sections of code, either a set or indefinite number of times depending on which one we choose. We're going to be looking at three: while, do while, and for loops.

while

A while loop is one of the most basic loops in your arsenal and is usually the outermost loop in an application. When execution enters a while loop it typically...

 

break/continue

Having the ability to loop sections of code is very important, but it has to be used carefully. We've seen that it's possible to create loops that never end, and another concern is ensuring that they're used efficiently. So far, the loops we've looked at have been small, and we've been happy to see them run through in their entirety. But what if we needed more control over our loops, perhaps to end one early? Thankfully, we have two important keywords to help us with that—break and continue.

break

break is a C++ keyword that will exit the current loop, with execution jumping to the next section of code if there is any. This keyword works with the different types of loop that we've covered so far, and we can demonstrate it nicely using a simple counting application, as shown in the following snippet:

// Break example.
#include <iostream>
#include <string>
int main()
{
    std::cout <<...
 

Summary

In this chapter, we've learned about program flow and how we can manipulate the flow of execution through our applications. This is fundamental for representing logical systems.

We started by looking at basic if/else statements. These allow us to branch our code based on conditions and are one of the most fundamental ideas in programming. With this branching ability, we're able to replicate logical systems and behaviors by controlling the flow of execution through our application. We then looked at some alternatives to the basic if/else statement, such as switch and ternary statements.

Next, we looked at a number of different loops. We started with while and do while loops; loops that run indefinitely so long as the condition they're checking is true. We then looked at for loops, which run for a set number of iterations. Finally, we looked at range-based loops, which are useful for iterating over collections. We ended by looking at how we can...

About the Authors
  • Dale Green

    Dale Green is a computer programmer who has worked in a range of disciplines, from full stack web development to C++ programming in AAA video games. As a passionate video game programmer, Dale has worked on multiple AAA titles for both PC and console, self-published a PC title, and authored a book on Procedural Content Generation for C++ Game Development.

    Browse publications by this author
  • Kurt Guntheroth

    Kurt Guntheroth has been a software engineer for nearly 40 years and has a mix of embedded, Windows, and Linux experience. Kurt has worked with C++ for over 20 years. Hes written a book on optimization of C++ programs called Optimized C++. He is working on a second book, tentatively called Nonstop C++, about building C++ programs that never crash.

    Browse publications by this author
  • Shaun Ross Mitchell

    Shaun Ross Mitchell is a games programmer with experience in many areas related to game development. Shaun has worked on platformers, tower defense, and VR games for consoles and PC. Shaun is t

    Browse publications by this author
Latest Reviews (3 reviews total)
As I wish for informations
I am reading this book in my spare time and also during my 'relaxation' time. I will update my review as I go along.
Ouvrage très pédagogique et bien conçu
Recommended For You
The Python Workshop

Learn the fundamentals of clean, effective Python coding and build the practical skills to tackle your own software development or data science projects

By Andrew Bird and 4 more
Machine Learning for Algorithmic Trading - Second Edition

Leverage machine learning to design and back-test automated trading strategies for real-world markets using pandas, TA-Lib, scikit-learn, LightGBM, SpaCy, Gensim, TensorFlow 2, Zipline, backtrader, Alphalens, and pyfolio.

By Stefan Jansen
The Deep Learning Workshop

Take a hands-on approach to understanding deep learning and build smart applications that can recognize images and interpret text

By Mirza Rahim Baig and 4 more
The Complete Python Course [Video]

Master Python and OOP concepts and structure your programs like a professional

By Codestars By Rob Percival and 1 more