Controlling Program Flow
Control flow refers to the order in which statements and instructions are evaluated and executed in a computer program. Code is run in order from the first line to the last, unless the computer runs across instructions that change the control flow, such as decision-making conditionals and interactive loops.
Conditional Execution
Conditional execution of code is implemented in C++ using the if ... else or Select..case construct. Multiple lines of code can be enclosed within statement blocks.
The if Statement: The if statement selects and executes statement(s) based on a predefined condition. The statement(s) are only executed if the condition evaluates to true. If the condition evaluates to false, execution is skipped and the program control passes to the statement following the if statement.
The syntax of the if statement is
if (condition)
{
statement 1;
statement 2;
}
The if-else Statement: The if - else statement causes one of the two possible statement(s) to execute, depending upon the outcome of the predefined condition.
The syntax of the if...else statement is
if (condition)
{
// code block if condition is true
Statement 1;
Statement 2;
}
else
{
// code block if condition is not true
Statement 3;
Statement 4;
}
Nested if-else Statement: A nested if-else statement contains one or more if-else statements and is validated against several different conditions, which themselves may be dependent on the evaluation of a previous condition.
if( expression1 )
// code block if expression 1 is true
statement1;
else if( expression2 )
// code block if expression 2 is true and expression 1 is false
statement2;
else
// code block if previous conditions are all false
statement3;
If expression1 is evaluated to true, statement1 is executed before the program continues. If the expression1 is not true, expression2 , is checked and if it evaluates to true, statement2 is executed. If both expression1 and expression2 are false, statement3 is executed. Only one of the three statements is executed.
Conditional Processing Using Switch-Case
The switch-case conditional statement enables a check on a particular expression against a host of possible constant conditions and performs a different action for each of those different values. Each case statement ends with a break statement that causes execution to exit the code block. In most situations, you will want a break ending each section however in some situations you may want to execute multiple case statements. If a break statement does not end the statement sequence associated with a case, then all the statements at and below the matching case will be executed
The following is the syntax of a switch-case construct:
switch(expression)
{
case optionA:
DoSomething;
break;
case optionB:
DoSomethingElse;
break;
default:
CatchAllWhenExpressionIsNotHandledAbove;
break;
}
The Conditional Operator '? :
The conditional operator is similar to an if-else statement and selects one of the two values or expressions based on a given condition. It cannot select more than one value at a time and execute more than one statement.
in the example below high value is set to the greater of two given numbers contained in num1 and num2
int highvalue = (num1 > num2)? num1 : num2;
Looping
Many tasks in a program are accomplished by carrying out a repetitive series of instructions, a fixed number of times or until a specific condition is met. A block of such code is called a loop. Each pass through the loop is called an iteration and the blocks of code are called compound statements.
While Loops
A while loop causes a code block to be executed repeatedly as long as a starting condition remains true. An expression follows the while keyword in parentheses. If the expression is true, the statements inside the loop block are executed and executed repeatedly until the expression is false. If the initial condition is not met code inside the block is not executed. In the following code sample, the while loop counts to 10 and exits the loop when the variable i is equal to 10
#include <iostream> int main() { int i; while (i <=10) //test condition { std::cout << ++i << "\n";//output value of i } }
The while keyword is preceded by the condition within parentheses. To note, this statement does not end in a semicolon. The statements inside the loop are surrounded by {} braces indicating the start and end of a localised block of code. The loop has the conditional expression i < =10 . The body of code will be executed while the value of i is lower than 10.
Do-While Loops
A do-while loop is a control flow statement that executes a block of code at least once. In contrast to a while loop which starts with a conditional expression before code execution, the do-while loop checks the condition after the block is executed.
#include <iostream> int main() { int i = 10; do { std::cout << ++i << "\n";//output value of i } while (i < 5);//test condition }
This loop’s conditional statement is only true when i < 5. Since i begins with a value of 10, this condition is never true however the body of the loop executes once. This occurs because the do-while loop does not evaluate the condition statement until after the loop’s statements are executed. A do-while loop always executes the body at least once.
For Loops
Is an iterative control flow statement that allows code to be executed a specific number of times. The exit condition is checked at the beginning of every loop, and the variable's value at the end of a loop. The syntax of a for loop is –
for ( init; condition; increment )
{
statement(s);
}
The optional init step is executed first, and only once, and allows the programmer to declare and initialise any loop control variables. If no initialisation is specified a semicolon must be used.
Following initialisation, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This process is repeated until the condition becomes false, after which the loop terminates
#include <iostream> int main() { for (int i = 0; i < 10; i++)//initialise loop { std::cout << i;//output value of i to screen } }
In the code section above, the for-loop is declared, and the variable i initialised to 0. The value of value i is then checked and if the exit condition (i<10) is not met the body is executed. The variable i is then incremented at the end of the loop and the process is repeated until the condition statement returns false and the loop exits.
Leaving any parameter blank in a for-next declaration means the condition will start with a null value. You can create an infinite loop by using for(;;)
Advanced for Loops – It is possible to create and run multiple loops within one statement. When the initialisation and action sections contain more than one statement, they are separated by commas –
for (int a = 0, b = 0; a < 10; a++, b++)
This loop has two variable initialisations: a and b, each separated by a comma. The loop’s test section tests whether a < 10 and both integer variables are incremented.
Nested Loops – Loops can be nested with one loop sitting in the body of another. The inner loop will be executed in its entirety for every execution of the outer loop. C++ allows at least 256 levels of nesting –
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.
}
The Range-Based for Loop – Introduced in C++11 the range-based loop executes on a predefined range of values such as those contained in an array
For example, given an array of integers, you would use a range-based for loop to read elements contained in the array –
#include <iostream> int main() { int myvalues[] = { 1, 88, 33, -5,13}; for (int aNum : myvalues) // range based for { std::cout << "The array elements are " << aNum <<"\n"; } }
Continue and Breaking
The break statement causes a loop to end immediately, instead of waiting for its condition to be false. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop
Continue resumes execution from the top of the loop. The code following it within the block is skipped. Thus, the effect of continue in a while , do...while , or for loop is that it forces the next iteration of the loop to take place, skipping any code in between.
#include <iostream> using namespace std; int main () { int a = 10; do { a=a+1; if( a == 15) //check if a=15. skip to end of loop { continue; } cout << "value of a: " << a << endl; } while( a < 20 ); return 0; }
Usually, programmers expect all code in a loop to be executed when the loop conditions are satisfied. Continue and break modify this behaviour and can result in non-intuitive code. Therefore, continue and break should be used sparingly
The Goto Statement
Goto performs a one-way transfer of control to another point in the program. This requires an unconditional jump ignoring any existing program flow such as nesting and does not cause any automatic stack adjusting. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:). It's advised to use goto statements with caution and preferably not at all since the use of goto statements can lead to an unpredictable flow of code, difficult-to-read programming(spaghetti code), and in some cases unpredictable variable states.
The syntax for the goto statement is
{
Start: // Called a label
UserCode;
goto Start;
}
Exiting the Program
Under normal circumstances, a C++ program terminates when execution reaches the closing brace of the main() function.
Program termination can, however, be initiated by the program by calling the library function exit() abort ad atexit. To use these functions, a program must include the header file <cstdlib>
Exit Function
The exit function terminates a C++ program and the argument value supplied to the exit function is returned to the operating system as a return code. Conventionally, a return code of zero means that the program was completed successfully and a value of 1 indicates that the program terminated with some sort of error. The syntax of this function is
void exit ( int status );
In addition, the header file also defines two constants for use as arguments to the exit() function:
define EXIT_SUCCESS
define EXIT_FAILURE
Abort Function
The abort function terminates the program immediately bypassing the usual run-time termination processing. The syntax for the atexit function is
void abort ();
Atexit function
The atexit function is used to specify actions that execute before the program terminates. The syntax for the atexit function is
int atexit (void (*func)(void));
The following short program demonstrates how to call a function before closing the program
#include <iostream> #include <cstdlib> using namespace std; void closing() { cout << "Program closure successful"; } int main() { int x; x = atexit(closing); if (x != 0) { cout << "Program Failure"; exit(1); } cout << "Program successful" << endl; return 0; }