if

if tests whether a certain condition has been reached, such as an input being above a certain number. The format for an if test is:

if (someVariable > 50)
{
  # do something here
}

The program tests to see if someVariable is greater than 50. If it is, the program takes a particular action. Put another way, if the statement in parentheses is true, the statements inside the brackets are run. If not, the program skips over the code.

The statements being evaluated inside the parentheses require the use of one or more operators:

Operators:

 x == y (x is equal to y)
 x != y (x is not equal to y)
 x <  y (x is less than y)  
 x >  y (x is greater than y) 
 x <= y (x is less than or equal to y) 
 x >= y (x is greater than or equal to y)

Coding Warning: Beware of accidently using = (e.g. if (x = 10) ), which sets a variable, instead of using == (e.g. if (x == 10) ), which tests whether x is equal to 10 or not. The latter statement is only true if x equals 10, but the former statement will always be true, because the value of x = 10 is true if the assignment is successful. Mistaking = for == will result in a test that is always passed, and which resets your variable as a (probably unwanted) side-effect.

if can also be part of a branching control structure using the if...else] construction.

Reference Home