An if statement consists of a boolean expression followed by one or more statements.
Syntax
if (expression) statement
expression is evaluated for boolean TRUE (≠0) or FALSE (=0). If TRUE, then statement is executed. If the boolean expression evaluates to FALSE, then the first set of code after the end of the if statement will be executed.
Whenever you see statement in a syntax guide, it may be replaced by a compound (block) statement.
Remember: spaces and new lines are not significant.
Example
Testing for TRUE
- if (x) vs. if (x == 1)
- if (x) only needs to test for not equal to 0
- if (x == 1) needs to test for equality with 1
- Remember: TRUE is defined as non-zero, FALSE is defined as zero
Questions
What will print if x = 5 ? … if x = 0?
if x = -82?
if x = 65536?
Nested if Statements
You can use one if or else if statement inside another if or else if statement(s).
Example
if else Statement
Syntax
if (expression) statement1
else statement2
expression is evaluated for boolean TRUE (≠0) or FALSE (=0). If TRUE, then statement1 is executed. If FALSE, then statement2 is executed.
Example
In this example, not only are we seeing a real-world if-else statement but we are also seeing an example of a more complex condition expression. Here, two conditions must be met: the frequency must be greater than 144.0 and it must be less than 148.0 for the first statement to be executed. If frequency does not fall in the range of 144.0 to 148.0, then the second statement will be executed (the one in the else clause). Notice that we are using the logical AND && operator and not the bitwise and & operator.
if else if Statement
Syntax
if (expression1) statement1
else if (expression2) statement2
else statement3
expression1 is evaluated for boolean TRUE (≠0) or FALSE (=0). If TRUE, then statement1 is executed. If FALSE, then expression2 is evaluated. If TRUE, then statement2 is executed. If FALSE, then statement3 is executed.