Control Statements

if Statements

Statements may be grouped using “{” and “}” and may contain the regular C if statement, or the if-else statement in the form “if ( <condition> ) <statement> [ else <statement> ]”. For example:

if ( x < 5 ) x = 0;

or

if ( y > x ) max = y;
else { max = x; y = 0; }

 

for Statements

The standard C for statement can be used in the form “for ( <initialization expression>; <expression>; <expression> ) <statement>” and work the same way as in C++. For example:

for ( int i = 0, x = 0; i < 15; i++ ) {
    x += i;
}

 

while, do-while Statements

The while and do-while statements can also be used in the form “while ( <condition> ) <statement>” or “do <statement> while ( <condition> )” and work the same way as in C. For example:

while ( myVar < 15 ) {
    x *= myVar;
    myVar += 2;
}

or

do {
    x *= myVar;
    myVar += 2;
}
while ( myVar < 23 );

 

switch Statements

A switch statement can be used to compare a variable with a number of values and perform different operations depending on the result. switch statements are of the form “switch ( <variable> ) { case <expression>: <statement>; [break;] ... default : <statement>; }” and works the same way as in C.

For example:

switch ( value ) {
    case 2 : { result = 1; break; }
    case 4 : { result = 2; break; }
    case 8 : { result = 3; break; }
    case 16 : { result = 4; break; }
    default : { result = -1; }
}

 

break and continue

break or continue can be used using the syntax “break;” or “continue;”. Use break to exit out of the current for, switch, while, or do block and transfer program control to the first statement after the block. Use continue to jump to the end brace of any for or while loop and continue execution of the loop. These work the same way as they do in C.

Copyright © 2006 Shawn (L. Spiro) Wilcoxen