Alternative Structures
In certain situations, it is necessary to execute instructions within a program only under certain conditions. Alternative structures (also known as decision structures) allow handling such situations.
The if Statement
The if statement is the most commonly used alternative structure.
Syntax
The if statement has two forms:
Variant 1
if( Expression )
Statement1
else
Statement2
Variant 2
if( Expression )
Statement1
Observations
- Statement1 executes only if Expression is true. Statement2 executes only if Expression is false. In no situation are both statements executed!
- Statement1 and Statement2 can be any kind of statements, including empty statements and even another if statement.
- If program logic requires it, Statement1 and/or Statement2 can be compound statements containing multiple instructions.
- Due to potential conversions, to determine if an expression is non-zero or zero, it is not necessary to use relational operators == and !=. Thus, the following sequences are equivalent:
if(Expression) …
if(Expression != 0) …
Similarly, the following sequences are equivalent:
if(!Expression) …
if(Expression == 0) …