Conditional Operators and Switch Statements
C++ has an operator that can be used as an alternative to an if-statement. This operator is called the conditional operator (?:). This operator can be used to replace an if-else statement of the following general form:
The above form of if-else can be alternatively written using ?: as follows,
It works in the same way an if-statement executes. The execution is in the following manner,
- expression1 is evaluated
- If the condition results into a true value in expression1 then expression2 is executed
- If the condition results into a false value in expression1 then expression3 is executed
Example:
can be alternatively written as,
How does a Switch statement work?
C++ provides a multiple-branch selection statement know as switch. This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed.
Syntax:
The expression is evaluated and its value is matched against the value of the constant specified in the case statements. When a match is found, the statement sequence associated with that case is executed until the break statement or the end of switch statement is reached. If a case statement does not include a break statement, then the control continues to the next case statement until either a break is encountered or end of switch is reached. When a break statement is encountered in a switch block, program execution jumps to the line of code immediately following the switch block i.e. outside the body of switch statement. The use of default statement is optional. It only executes when no case conditions match.
Example: Following code shows the implementation of switch statement
Comments - No Responses to “Conditional Operators and Switch Statements”
Sorry but comments are closed at this time.