There are some moments in life when we have to make decisions, and according to these decisions, we decide how things will go next. Similarly, in computer programming, we need to make some decisions in our code flow based on a certain set of inputs, and these decisions tell us which code block to execute next and which code block to skip.
Getting Started with ” if ” conditions
This is the simplest decision-making statement that can be used to decide which block of code will be executed next. This decision is based on whether a certain condition evaluates to FALSE or TRUE.
Example:
if(some_condition) statement;
In this example, if the variable named “some_condition” does not evaluate to TRUE, the code block that follows will not be executed.
Example:
if(some_condition) statement_1; statement_2;
In this example, similarly, if “some_condition” evaluates to TRUE, “statement_1” is executed. However, in this case, since curly braces were not explicitly used following the if condition, only the statement that follows the condition will be executed. Meaning in this case, if “some_condition” evaluates to FALSE, only “statement_2” will be executed and “statement_1” will be skipped since it is the only statement associated with the if condition.
Example:
if(some_condition) { statement_1; statement_2; }
Here curly braces are used to associate one or more statements to the if condition.
Example program to:
- evaluate the input variable “x”
- if “x” is greater than 10, set it to 20
#include <iostream> using namespace std; int main() { int x = 5; if(x > 10) { x = 20; } cout << "x equals: " << x << endl; }
Output:
x equals: 5
Here in this example, the value “x” is not greater than 10, then its value remains unchanged.
“if-else” statements
The if condition only executes the following block of code if the condition evaluates to TRUE. Now, what happens if you want to execute a separate block of code in the case of TRUE and another block of code in the case of FALSE? In this case, we use the “else” statement.
Example program to:
- evaluate the input variable “x”
- if “x” is greater than 10, set it to 20
- if “x” is less than or equal 10, set it 0
#include <iostream> using namespace std; int main() { int x = 5; if(x > 10) { x = 20; } else { x = 0; } cout << "x equals: " << x <<endl; }
Output:
x equals: 0
Here the condition whether “x” is greater than 10 evaluates to FALSE. Therefore, the block of code that follows the “else” statement is executed setting “x” to zero.
“if, else-if and else” statements
Now imagine you have a variable that you want to check against a certain value, and in case your check does not evaluate to TRUE, you would like to check it against another value. Here comes the work of the “else-if” statement.
Example program to:
- check the input variable “x”
- if “x ” is less than 10, set it to 0
- if “x” is less than 20, set it to 10
- otherwise, leave it unchanged
#include <iostream> using namespace std; int main() { int x = 15; if(x < 10) { x = 0; } else if(x < 20) { x = 10; } cout << "x equals: << x << endl; }
Output:
x equals: 10
Here the value “x” has not satisfied the first condition yet satisfied the second. Therefore, the value “x” is set to 10.
Nested “if and if-else” statements
What if you need to check a variable against a certain value, and if your check is satisfied, you need to check it against another value? One way to do this is that you can use “if” statements inside of other “if” statements.
Example program to:
- check input variables “x” and “y”
- if both, “x” and “y” are greater than 10, set “y” equals “x”
#include <iostream> using namespace std; int main() { int x = 15; int y = 20; if(x > 10) { if(y > 10) { y = x; } } cout << "x equals: << x << endl; cout << "y equals: << y << endl; }
Output:
x equals: 15
y equals: 15
For sure there is another way to implement this example using the “&&” operator as in the following code snippet.
#include <iostream> using namespace std; int main() { int x = 15; int y = 20; if( (x > 10) && (y > 10) ) { y = x; } cout << "x equals: << x << endl; cout << "y equals: << y << endl; }
Output:
x equals: 15
y equals: 15
In addition to the “&&” operator, you can also use the “||” operator that represents logic or operation, OR the exclamation mark “!” that represents the logic NOT operation.
Switch Statement in C++
Switch case statements are mainly used to replace long if statements and are specifically utilized if you need to check your variable against a whole lot of possible values. Just like if conditions, switch cases allow you to change your path of execution, favoring branches over branches in an easy and readable way.
Usage and syntax:
switch (var) { case a: // execute if var = a break; case b: // execute if var = b break; default: // execute if var is not equal a or b }
The default case can be compared to the “else” statement, where this block of code is executed if and only if all previous conditions were not satisfied.
Example program to:
- evaluate the input variable “x”
- if “x” equals 30, set it to 20
- if “x” equals 20, set it to 10
- otherwise, set it to 0
#include <iostream> using namespace std; int main() { int x = 20; switch(x) { case 30: x = 20; break; case 20: x = 10; break; default: x = 0; } cout << "x equals: << x << endl; }
Output:
x equals: 10
Note that the “break” statement tells the compiler to stop executing the switch case statement.
Some points to consider when writing switch case statements
- The expression passed to the switch statement needs to evaluate to a constant value or else it will not be valid.
- You can not use duplicated cases. For example, if “x” is checked to be equal “a” in a case, you can not repeat this same check again in a different case.
- The default case is optional, which means you can just not write it if you want. However, it is still recommended that you write your default scenario.
- The break statement is optional, if not present, the code will continue executing and evaluate the next case.
- Nesting of switch statements is allowed, which implies using a switch case inside a specific case for example. On the other hand, it is not recommended because it makes your code not readable and complex to debug.
Jump Statements in C++
C++ break
The “break” statement is typically used to terminate a loop even if the loop continuity condition is not satisfied yet.
Example program to:
- initialize integer variable “x”
- loop from 0 to 10
- if 5 equals loop iterator, break from the loop (use if conditions)
- otherwise, set “x” equals loop iterator
#include <iostream> using namespace std; int main() { int x, i; for(i=0; i<=10; i++) { if(i == 5) break; else x = i; } cout << "x value equals: << x << endl; }
Output:
iterator equals: 4
In this example, you can see how the value of “x” is 4 because the loop was stopped before assigning the iterator’s value to “x”.
C++ Continue
Unlike the break statement, “continue” forces the loop to go to the next iteration. On the other hand, it is used when you do not want the code block associated with the loop to be executed for this specific iteration.
Example program to:
- initialize integer variable “x”
- loop from 0 to 10
- if 5 equals loop iterator, continue loop execution (use if conditions)
- otherwise, set “x” equals loop iterator
#include <iostream> using namespace std; int main() { int x, i; for(i=0; i<=10; i++) { if(i == 5) continue; else x = i; cout << "x value equals: << x << endl; } }
Output:
x value equals: 0
x value equals: 1
x value equals: 2
x value equals: 3
x value equals: 4
x value equals: 6
x value equals: 7
x value equals: 8
x value equals: 9
x value equals: 10
Notice how assigning the value 5 to “x” was skipped using the continue statement.
Goto Statement
The developers refer to Goto statements as unconditional jump, which they can use to jump from one block or label to another label or block in the code. The goto statement does not need any condition to be true to make any jump or move to any label. Whenever the code stumbles upon a goto statement, it moves to the requested label without checking any condition and starts executing the code from that label. Moreover, the users can choose to use the Goto statement inside the if-else statement block or use it in the simple code block without any conditions.
Goto Statement inside the If-Else Block
Below is the sample code to demonstrate its working inside the if-else block:
int main(){ int k =0; Label1: k++; If (condition1) { // any user-defined condition Goto label1; } else{ k =0; } }
The program checks if condition1 is true; it shifts the flow to Label1 and starts executing the instructions from there. Else, it continues to run the instructions line-wise.
Goto Statement inside the Basic Code Block
Below is the sample code to demonstrate its working inside the basic code block:
int main() { int x=1; Label1: x = x+1; goto Label1; }
In the above example, the program declares an integer variable x and assigns it the value “1.” Then, it moves on to Label1 and increments the x’s value by 1. It moves to the next instruction and finds a jump here, due to which it shifts the code flow to label1 again and increments the x’s value again, and gets stuck in an infinite loop. Therefore, the users must make sure that the program does not get stuck inside an endless loop, and there should be some condition or check which can make it break the loop.
Note: the users must define the labels before using them with the goto statement.
Return Statement
In c++, the developers can use the return statement inside the functions to return to the callee statement, which called the function in the first place. Moreover, as it shifts the code flow back to the callee, the program starts the callee function’s execution.
Furthermore, the return statements may or may not be conditioned and can return some output such as integer, array, object to the caller function.
Return Statement in Void Function
The void function is the function that does not return any value. Below is the sample code to demonstrate the return statement in a void function:
void print() { cout << “Hello! I am inside the print function” <<endl; return; //can skip it in this case } int main(){ print(); cout << “Hello! I am back in the main function” << endl; return 0; }
In the above example, the function does not return anything because its returns type is void. The main function calls the print() function, which prints “Hello! I am inside the print function” and then returns to the main function, which prints “Hello! I am back in the main function” on the user’s screen. Furthermore, the users can choose to skip the return statement in the void function with unconditional statements. In that case, the function will execute the instructions line by line and return the control to the callee function automatically.
Return Statement in the function with Return Value
Additionally, below is the sample code to demonstrate the return statement in the fruitful function:
bool even(int x) { if (x/2 == 0)return 0; return 1; } int main(){ bool result = even(2); cout << result << endl; return 0; }
In the above code example, the even function takes an integer as its parameter and checks if it is even or not. If the value is even, it returns 0; otherwise, it returns 1 to the main function, storing the return value in a boolean variable and prints it on the user’s screen.
The “?” Operator
The developers can use the question marks (?) operator in C++ instead of “if,” “else” statements to control the code flow or make decisions.
Replace the If-Else Statement with “?”
Below is the general code for if, else statements:
if(condition1) //expression1 else //expression2
The users can rewrite the above code in the below form.
condition1? Expression1: Expression2
This example replaces the if, else statements by “?” and makes the code more compact and reader-friendly.
The “?” operators check whether condition1 is true or not. If it is true, it evaluates Expression1. Otherwise, it moves onto Expression2, evaluates it, and Expression2’s value becomes the value of the expression under consideration.
Evaluation and Assignment using “?”
Below is the example to demonstrate the evaluation and assignment using “?” operator:
int a, b = 70; a = (b <70)? 30 : 10;
In the above example, the operator checks if the value of b is smaller than seventy or not. If yes, it assigns the value thirty to “a”; otherwise, it sets the value ten of variable a.