4.2. Selection Statements

4.2.1. if – else

We discussed this in Topic 1. Recall the basic form of if statements:

if( expr) statement;

if( expr ) {
   statement1;
   statement2;
}

if( expr ) {
   code block;
} else {
   code block;
}

Also, recall the dangers of the “dangling” or ambiguous else.

if( expr )
   if( expr )
      statement;
   else
      statement;

4.2.2. The goto statement

The goto statement is strongly discouraged.

label: begin

...

if( attempts == 0 ) goto begin;

The only possible argument for a goto is if the code is nested several layers deep into loops and an immediate switch to elsewhere is needed. Even here, other methods achieve the same result.

4.2.3. The break and continue statements

break and continue provide additional controls for loops. [1]

break tells the program counter to exit the loop and continue executing the code following the loop.

continue is an instruction to stop with the current execution of the loop body and skip to the end of the body of the loop and continue as if the bottom of the loop had been reached via normal program execution.

4.2.4. The switch statement

The switch is a multi-way conditional statement generalizing the ifelse statement.

switch( val ) {
case 1:
   counter++;
   break;
case 2:
case 3:
   counter--;
   break;
default:
   counter = 0;
}
  • The controlling expression of a switch statement, must be an integer.
  • Notice that the end of each case block is a break statement.
  • If break is missing from a case block, execution falls through to the next block. In the example above, if val == 2, then the same code for when val == 3 is executed.

4.2.5. Conditional Operator

  • The operator ? : is a ternary operator. It takes three variables or expressions as its operands.
  • Syntax: expr1 ? expr2: expr3
  • First, expr1 is evaluated, if it is true (non-zero), then the whole expression reduces to expr2, which is then evaluated.
  • If expr1 is false (zero), then the whole expression reduces to expr3, which is then evaluated.

The following two expressions are identical.

if (y < z)
   x = y;
else
   x = z;


x = (y < z) ? y : z;

Here is another example.

int a = 1, b = 2;
double x = 7.07, y;

printf( "%d\n", ((a == b) ? a -1 : b + 1));     ---  3
printf( "%lf\n", ((a-b) < 0 ? x : a + b));      ---  7.07
printf( "%lf\n", ((a-b) > 0 ? x : a + b));      ---  3.0

In the last example, because of the mixed data type in the conditional operation, all data types are converted to double type.

Footnotes

[1]break is also used with the switch statement.