C++: Flow control with if statement

This entry is part 10 of 61 in the series C++

Like most languages, C++ provides an if statement that supports conditional execution.

We can use an if to check for each condition.  You can actually stack up the many if statements to check for the different conditions.

The example below checks for 2 conditions.

#include <iostream>
#include <string>
using namespace std;

void main()
	string singer = "Taylor Swift";
	int count = 6;

	if (singer == "Taylor Swift")
		cout << "I am a fan.";

	if (count == 5)
		cout << "This is her fifth album.";

	cout << endl;


For an if statement, if an expression evaluates to true, it will proceed to execute other statements inside the curly braces.

The first expression singer==”Taylor Swift” will evaluate to true and so the line inside the curly braces is printed out.

For the second expression count==5, as we have set count to be 6 earlier, this expression will not evaluate to true.  So it will not execute the cout statement inside the loop.



Series Navigation<< C++: A string class and its method
C++: The if-else statement >>
Posted in