Controlling execution flow
C++ provides many ways to test values and loop through code.
Using conditional statements
The most frequently used conditional statement is if
. In its simplest form, the if
statement takes a logical expression in a pair of parentheses and is immediately followed by the statement that is executed if the condition is true
:
int i; std::cin >> i; if (i > 10) std::cout << "much too high!" << std::endl;
You can also use the else
statement to catch occasions when the condition is false
:
int i; std::cin >> i; if (i > 10) std::cout << "much too high!" << std::endl; else std::cout << "within range" << std::endl;
If you want to execute several statements, you can use braces ({}
) to define a code block.
The condition is a logical expression and C++ will convert from numeric types to a bool
, where 0 is false
and anything not 0 is true
. If you are not careful, this can be a source of an error...