C++ Syntax: if (args)


The if statement has the form:-
if ( expression ) statement
If the expression evaluates to true (not zero) the following statement, which is normally a compound statement is executed. An optional else statement may follow immediately (no intervening statements), for example:- if ( a > b ) print " a > b\n"; else print "a <= b\n";

Usage Notes

Alternatives to if (args)

The switch statement is a good way to perform a multi-way branch on a single value.

Multi-way ifs

There is no elseif statement. To make a multi-way branch use a set of nested ifs, for example:- if ( a > b ) print "a > b\n"; else if (a == b ) print "a == b\n"; else print "a < b\n"; Note in the above example that the else statement must belong to the second if (the first if has an intervening statement). To be able to match an else to an outer if requires the use of a compound statement e.g.:- if ( a >= b ) { if (a == b ) print "a == b\n"; else print "a > b\n"; } else print "a < b\n"; Now the second if is hidden inside the compound statement and the second else is the next statement after the first if. Also note how important it is to align statements to improve readability!
Go Back to the The C++ Crib Top Page

If you have any comments about this page please send them to Nick West