3.2.1 if

Previous Index Next


The if statement is used to control the flow of code execution based on the evalution of an expression. The if can take the following forms:
if ( Expression ) StatementIfExpressionTrue
if ( Expression ) StatementIfExpressionTrue else StatementIfExpressionFalse
For instance
int x = 5;         // declare a integer initialised to 5
if ( x > 4)        // if x is greater then 4
   x = x + 5;      // add 5 to it.
if ( x < 10)       // if x is less then 10
   x = x +4;       // add 4 to it
else               // otherwise
   x = x - 2;      // subtract 2 from it
if ( x == 20)   // if x is equal to 20
 {
  x=5;          // set x equal to 5
  x=x * 2;      // set x equal to x times 2
 }
if (x <= 23 )  //if x is less then or equal to 23
 {
  x = 0;       // set x equal to 0
  x = x +1;    // add 1 to x
 }
else           // otherwise
 {
  x=5;         // set x equal to 5
  x=0;         // set x equal to 0
 }
if statements can also be nested. For example:
int y = 7;      // declare an integer an initilize to 7
if ( y > 5 ) // if y is greater then 5
   if ( y < 8) // if y is less then 8
      y = 0; // set y = 0