Modern C++: The Good Parts/Now it gets interesting.

Up to now all of our programs have been very straightforward: Start at the top and read each line once until you get to the bottom. That changes now, because that's not really a very useful way to write a program. Useful programs usually repeat some things, or decide to not do some. This chapter covers how to select a course of action on the fly.

CodeEdit

#include <iostream>
#include <string>

int main()
{
	std::string input;
	int a, b;
	int greater;
	// This one starts out with a value.
	bool canDecide = true;

	std::cout << "Enter two integers to compare.\n";

	// Take input.
	std::cin >> input;
	// Parse it as an int.
	a = std::stoi(input);
	
	// Take input.
	std::cin >> input;
	// Parse it as an int.
	b = std::stoi(input);
	
	// This is equality, and it might be true now and false later.
	if(a == b)
	{
		// = does not mean equality, which means we can do this.
		canDecide = false;
	}
	else if (a < b)
	{
		greater = b;
	}
	else
	{
		greater = a;
	}
	
	if(canDecide)
	{
		std::cout << greater << " is the greater number.\n";
	}
	else
	{
		std::cout << "The numbers are equal.";
	}
}

ExplanationEdit

bool is short for Boolean, which means yes or no, true or false. In this case the bool variable "canDecide" is initialized to the value true. Basically, the program assumes it "canDecide" which number is greater, until it sees evidence to the contrary. Overwriting bools in this way can be very useful.

== is the equality operator; it determines whether two values are equal, and returns true or false. Note: It does not change the value of anything.

Anything that looks like if(...){...} is an if statement. a == b is an expression which evaluates to a bool. An expression is some code which can be resolved to a value. The curly brackets just after if(a == b) contain code which will run if a equals b.

else if means "Otherwise, if..." and is only tested if the condition (the bool) is false for the first if statement. else by itself doesn't test any condition, but only runs if none of the if statements in its chain have been run.

When some logic is selected for execution in this way, "control" is said to "flow" into the logic. So if statements are considered control flow statements or control structures, a set which contains some other constructs to be introduced later.

ExercisesEdit

  • Write a calculator, asking the user for two floats and an operator and then printing the result.

VocabularyEdit

bool
one of two possible values, true or false. Also called a condition.
expression
some code which can be resolved to a value.
if statement
runs if its condition is true. Syntax: if(condition){ }
control flow
which code runs, and in what order.
control structure
a statement which modifies control flow. Also called a control flow statement.
Modern C++: The Good Parts
 ← Number crunching Now it gets interesting. Switching things up →