Complex Branching Concepts

Outline:

if-else

The if-else is the complete fundamental building block - based on a single condition, you choose between two possibilities, whereas for an if alone, you conditionally do one thing.
        if( condition )
	{
            BB1;
	}
	else
	{
            BB2;
	}
	if (x < 0.0)
	{
		printf("x is negative.\n");
	}
	else
	{
		printf("x is non-negative.\n");
	}
How it works:

If the condition is true, the BB1 will execute and then continue with the code after the close curly brace. If the condition is false, it will skip over BB1 and go to BB2. Once it completes BB2, it will continue with the code after the curly brace.


When to use this construct:

When you want to choose between two actions.

nested if-else

One way to choose between three choices is a nested if-else statement. Imagine instead of negative and non-negative, we want to identify negative, zero, and non-negative. With nested if statements, we do not view it as choosing between three - we first choose between two categories (e.g. positive and non-positive) and then separately distinguish between one of the others (non-positive is split between zero and negative).

if and else basic blocks (BB) can contain any arbitrarily complex code - it could include loops, sequential code intermixed with code, etc. Once you are inside the BB, the program can be anything.

        if( condition1 )
	{
            BB1;
	}
	else
	{
		if (condition2)
		{
            		BB2;
		}
		else
		{
			BB3;
		}
	}
	if (x < 0.0)
	{
		printf("x is negative.\n");
	}
	else
	{
		if (x > 0.0)
		{
			printf("x is positive.\n");
		}
		else
		{
			printf("x is zero.\n");
		}
	}
How it works:

If condition1 is true, the BB1 will execute and then continue with the code after the close curly brace. If condition1 is false, it will skip over BB1 and go to the else clause. The else clause contains more code, including another if statement. It will then evaluate the condition2. If condition2 is true, then it will run BB2. If condition2 is false, it will run BB3. Once it finishes, it will continue with code after the last curly brace.

The if statement could contain anything - not just a nested if statement. There can be loops, function calls, etc.
When to use this construct:

When you do not have a simple case. You want to choose between two things, but then you have further subdivisions of the task.

if-else if-else if

  • This is a more appropriate choice for when you are choosing between more than two options. Nesting is a general technique for complex code within if statements. if-else if-else if is more specifically for choosing between many actions.
  • When an if-else is used in the false block of another if-else, that is termed a sequential if, ( or cascaded if ) :
  •         if( condition1 )
    	{
                	BB1;
    	}
    	else if (condition2)
    	{
             	BB2;
    	}
    	else if (condition3)
    	{
    		BB3;
    	}
    	else // doesn't always need an else
    	{
    		BB4;
    	}
    
    	if (x < 0.0)
    	{
    		printf("x is negative.\n");
    	}
    	else if (x > 0.0)
    	{
    		printf("x is positive.\n");
    	}
    	else
    	{
    		printf("x is zero.\n");
    	}
    
    How it works:

    If condition1 is true, the BB1 will execute and then continue with the code after the close curly brace. If condition1 is false, it will skip over BB1 and go to the next condition. It will then evaluate the condition2. If condition2 is true, then it will run BB2. If condition2 is false, it will run BB3. Once it finishes, it will continue with code after the last curly brace.

    When to use this construct:

    When you are choosing between more than 2 actions.

    switch

    A switch statement is both a syntactic tool used in a specific circumstance and a structure that leads to a much more efficient implementation. A switch statement should be used when you are comparing a single variable to possible constant values:
        const int left = 1, right = 2, up = 3, down = 4; // For improved readability   
        int direction;
        . . .
        printf( "Please enter a direction, 1 for left, 2 for right, ... " );
        scanf( "%d", &direction );
    
        if( direction == left )
            x--;
        else if ( direction == right )
            x++;
        else if ( direction == up )
            y++;
        else if ( direction == down )
            y--;
        else
            printf( "Error - Invalid direction entered.\n" );
    switch( variable_integer_expression ) {
      case constant_integer_expression_1 :
    	BB1;
    
      case constant_integer_expression_2 :
    	BB2;
    	break; // ( Optional - See below )
    
      case constant_integer_expression_3 :
    	BB3;
    
      default: // Optional
    	BB4;
    } // End of switch on . . .
    
    const int left = 1, right = 2, up = 3, down = 4; // For improved readability   
    int direction;
    . . .
    printf( "Please enter a direction, 1 for left, 2 for right, ... " );
    scanf( "%d", &direction );
    
    switch( direction ) {
    
         case left:
              x--;
              break;
    
         case right:
               x++;
               break;
    
         case up:
              y++; 
              break;
    
         case down:
              y--;
              break;
    
         default:
         	  printf( "Error - Invalid direction entered.\n" );
              break;
    
    } /* End of switch on direction */
    How it works:
    When to use this construct: To illustrate the usefulness of not using the break every time, here is a second example. This is a very common usage of switch statements - menus. A user enters a menu choice, and the switch statement determines what to do based on what character the user entered.
    bool done = false;  // Assumes stdbool.h has been #included
    char choice;
    
    while ( ! done ) {
    
        // Code to print out a menu and ask for choice omitted
    
        scanf( "%c", &choice );
    
        switch( choice ) {
    
            case 'E':
            case 'e':
    	    EnterData();
                break;
    
            case 'H':
            case 'h':
            case '?':
    	    PrintMenu();
                break;
    
            case 'Q':
            case 'q':
                done = true;
                break;
    
    	// could have more choices.....
            case 'C':
            case 'c':
                /* Code here to handle Calculations */
                break;
    
    	// end with the default for invalid input
            default:
                printf( "Error - %cinvalid\n", choice );
                printf( "Choose 'H' for help.\n";
                break;
    
        } /* End of switch on menu choices */
    
    } /* End of infinite while loop */
    

    The Conditional Operator

    Note: You are not allowed to use this operator in your code. This is provided so you understand how to read it, not use.

    Earlier we looked at unary and binary operators under C.  In addition, the C language contains one ternary operator, known as the conditional operator, ?:

    condition ?  true_clause : false_clause