Department of Engineering

IT Services

Control statements

Control statements determine the order in which nested statements are executed. In the following, b denotes a boolean expression, i is a variable of any simple type and s, s1 and s2 are single statements. Where more than one statement is required in a control structure, a block should be used.

  • IF
       if (b) s1;           // if b is true, s1 is executed
    
       if (b) s1; else s2;  // if b is true, s1 is executed, but
                            // if b is false, s2 is executed
    
       if (b)
       {
          // executed only if b is true
          s1;
          s2;
       }
    
       if (b)
       {
          // executed only if b is true
          s1;
          s2;
       }
       else
       {
          // executed only if b is false
          s3;
          s4;
       }
    

  • SWITCH
       switch (i)
       {
          case i1:
             s1;      // s1, s2 executed if i == i1
             s2;
             break;
    
          case i2:
             s3;      // s3 executed if i == i2
             break;
    
          // ... more cases as required
    
          default:
             s4;      // s4 executed only if none of the cases matches
             break;
       }
    
    i1 and i2 are constants of the same type as variable i, which must be an integral type.

  • WHILE
       while (b) s1;  // s1 executed repeatedly while b is true
    
       while (b)      // s1, s2 executed repeatedly while b is true
       {
          s1;
          s2;
       }
    
    Note that if b is false, s1 or s1 and s2 will not be executed at all.

  • DO...WHILE
       do s1; while (b);    // s1 executed repeatedly until b is false
    
       do                   // s1, s2 executed repeatedly until b is false
       {
          s1;
          s2;
       }
       while (b);
    
    Note that s1 or s1 and s2 are executed at least once (even if b is false).

  • FOR
       for (s_initialisation; e_boolean; s_increment)
       {
          s1;
          s2;
       }
    
    is equivalent to (but clearer in intent than):
       s_initialisation;
       while (e_boolean)
       {
          s1;
          s2;
    
          s_increment;
       }
    
    for example:
       for (int i = 0; i < 20; i++)
       {
          s1;      // s1, s2 executed 20 times
          s2;      //   with i = 0 ... i = 19
       }