C++/Conditional Statements

From Wikiversity
< C++
Jump to: navigation, search

First, a couple notes (since I've pretty much made this tradition in my lessons). So...

  • Firstly, hopefully you have read the lessons to date. You should be well versed in simple input/output as well as variables.
  • Secondly, hopefully the lessons are teaching you some valuable skills in C++. Once again, it is awesome to see people adding on to the lessons.

As the name implies, conditional statements specify whether another statement or block of statements should be executed or not. These are often called "selection constructs". The two general types are "if...then" and the "switch...case" construct. Note that there is no looping involved here, but that conditionals are involved in loops.

Comparison Operators[edit]

The conditions tested are specified using comparison operators. These operators cause the immediate statement in which they are contained to return a Boolean value of either true or false. (Note that in certain circumstances they may evaluate to 0 or 1; be careful combining conditional statements with arithmetic)

The following comparison operators are available:

  • Equality: ==, or Inequality: != of any primitive data type (int, char, float, bool, etc.) These are binary operators (take two operands) and are specified using infix notation (which means that the operator goes in between the two operands).
  • Greater-than: >, Greater than or equal to: >=, Less-than: < and Less than or equal to: <= are also binary operators using infix notation. Use only with numeric data types; there are specific functions for comparing other data types.
  • Negation: ! is a unary operator, and prefixes the operand.

Examples:

Statement Result
5 == 5
true
7 != 5
true
'a' == 'b'
false
6 > 9
false
4 <= 4
true
!true
false
true!
syntax error

The if...else Conditional[edit]

There are two variations to the if...then conditional. Let us take a simple case and explain it line-by-line.

1 if (x == 7) {
2      //this code is executed only if x does indeed contain the integer value 7
3 }
4 else {
5      //this code is executed if the preceding if condition evaluated to false
6 }

Explanation:

  1. This is the first line. Note that there is space between the keyword if and the opening parenthesis. Inside the parentheses is the condition; in this case it is a test for equality. It is good practice to use the same type arguments (not comparing floating-point values to characters). Note also the left curly brace {. This symbol denotes a block of multiple lines of code. Without it, the conditional would only refer to the statement immediately following it. It is good practice to always use the braces.
  2. This comment represents the body of the conditional statement.
  3. The right curly brace is essential; it matches the opening brace on line 1 and signals the end of the if body.
  4. This line is optional. If there is a sort of "default" behavior that should be carried out, it would be placed here. The else clause does not belong by itself, only directly following an if clause.
  5. This is the body of the else clause.
  6. This curly brace is also essential; it matches the opening brace on line 4 and signals the end of the else body.

The body of the else block can be another if statement. This is known as "nested conditionals" because the conditionals are indeed nested; that is, placed inside of one another.

The switch...case Construct[edit]

This tests an input variable for equality with any number of cases and then executes the corresponding code. The syntax follows:

 1 switch (a) {
 2     case 1:
 3         //some statements
 4         break;
 5     case 2:
 6         //some more statements
 7         break;
 8     default:
 9         //even more statements
10         break;
11 }

Again, here is a line-by-line explanation:

  • Line 1: The opening line is very similar to the if construct, described above. The only difference is that the switch...case construct only uses int values and character constants or character literals. For this reason, the switch-case can come in handy but it is limited to these circumstances.
  • Line 2: For each expected value, code a line such as this one. The 1 means that if a does contain an integer value equal to 1, execution will begin following the colon on this line. Execution will continue blindly, so,
  • Line 4: contains a break statement that forces execution outside of the switch block.
  • Line 8: The default block is similar to the else block in a normal conditional. It is chosen if none of the previous cases matched the value of the condition variable.

Note, the break statement can be under-used to the programmer's advantage. If multiple values of the condition variable would lead to executing the same code, the cases can be listed one after another like this:

...
 case 1:
 case 2:
 case 4:
     //code common to those three cases.
     break;
 ...

The Conditional Expression[edit]

There are expressions of a special kind, the conditional expressions, these are not statements, but they are one sort of contraction of the if...then construct. This kind of expression can help to produce highly readable assignment statements fitting onto one line of the source code. This is the syntax (there is no semicolon at the end, since it is not a statement but an expression embeddable into even larger expressions):

( condition ) ? expressionIfTrue : expressionIfFalse

First the condition is evaluated and the side effects of this evaluation carry out their impact on the local environment. If the result is true then only the expressionIfTrue is evaluated (causing side effects) and this second result is the value of the whole conditional expression, and the expressionIfFalse is not evaluated (and hence cause no side effects). If the condition evaluates to false, then the situation is converse, the resulting values is given by the evaluation of the false branch of the conditional expression, and the true branch is not evaluated.

Common use of the conditional expression is to assign the value x or y to a, depending on an easily decidable condition, say x>y. See the sample code below:

int a = ( x > y ) ? x : y;
 //this is equivalent to:
 int a;
 if (x > y)
     a = x;
 else
     a = y;

As you can see, this makes simple conditionals all the simpler.

Use the conditional expression only if you feel that it really enhances the readability.

See if you can come up with a few usages of the conditional constructs you have just learned.

Where To Go Next[edit]

Topics in C++
Beginners Data Structures Advanced
Part of the School of Computer Science