Objects First |
Statement S1 is executed first, followed by S2, then S3, etc.
However, we often need to choose different sets of operations depending on the data. For instance, your bank's computer, when presented with a withdrawal request, will act in a markedly different manner if you have enough funds to cover the request from that if your request exceeds your available funds! To accomplish this, we have branching statements. These alter the flow of control in a program.
The most common of these is the if .. else .. statement.
Formally, it looks like this:
| if( expression ) statement; |
| [ else statement; ] |
where the brackets [ and ] indicate that the else part is optional.
Thus we could write:
if ( withdrawal_amount <= balance ) {
process_withdrawal( withdrawal_amount );
}
else {
printf("Insufficient funds!\n");
}
Note that statement can mean
if ( withdrawal_amount <= balance )
process_withdrawal( withdrawal_amount );
else printf("Insufficient funds!\n");
but that I have chosen to include the braces anyway.
Style note
I recommend that you include the braces whether they are needed or not. This makes later editing of the program less susceptible to errors.
and the implementation might look like this:
#include "Boolean.h"
int AreaWithinLimits( Rectangle r, int lower, int upper ) {
if ( Area(r) < lower ) {
return FALSE;
}
else {
if ( Area(r) > higher ) return FALSE;
else return TRUE;
}
}
Note that this assumes that we've defined two constants
in Boolean.h:
#define TRUE 1
#define FALSE 0
However, although this will work fine, we can make it simpler!
int AreaWithinLimits( Rectangle r, int lower, int upper ) {
if ( (Area(r) < lower) || (Area(r) > higher) ) {
return FALSE;
}
else {
return TRUE;
}
}
Here, we've used the fact that an if
statement takes
any expression and combined two tests into one expression,
linking the two conditions by the logical or operator,
||.
Note the double vertical bars of the logical or operator -
not the single vertical bar of the arithmetic or operator.
just like the problem with ==. |
Both
and
are perfectly legal C expressions - so the compiler can't warn you that you made a mistake.
the 3 logical operators (==, &&, ||) all have double symbols. |
int AreaWithinLimits( Rectangle r, int lower, int upper ) {
return ( (Area(r) >= lower) && (Area(r) <= higher) );
}
int AreaWithinLimits( Rectangle r, int lower, int upper ) {
if ( Area(r) < lower ) return FALSE;
else
if ( Area(r) > higher ) return FALSE;
else return TRUE;
}
To which if does the second else belong? The standard specifies that it belongs to the immediately preceding if.
Style note
This is just another reason for using the braces whether they are needed or not.
It saves anyone (you while writing the program and anyone following you while reading it) from needing to remember this rule!
Key terms |
| Continue on to The character class | Back to the Table of Contents |