You are on page 1of 5

6 Conditional Statements

Read and study this section with care. It is fundamental to programming and con-
tains new ideas and some complex syntax.

6.1 Introduction
Up to now we have been dealing with programs that read numbers, do fixed calcu-
lations in a pre-specified order and output results. This is not much of a PROGRAM!
The main power of computing is conditional control over which statements (parts
of the program) are executed in which order, and how many times. This is generally
called Flow Control and will be considered in two sections, the first dealing with
Conditional Statements and the second dealing with Loops, which you will deal
with after the next checkpoint.

6.2 Conditional Statements


In “C” conditional execution is mainly accomplished by the if statement which in
its simplest form is:

if (<-- logical statement -->)


{
<-- First line of optional code -->;
<-- Second line of optional code -->;
<-- .... -->;
<-- nth line of optional code -->;
}

When the “<logical statement>” is TRUE then the piece of optional code is
executed, else it is skipped over.
Note the following points about the syntax,

1. There is no “;” after the if() statement. This is a very common source of
programming bugs!

2. The optional code is enclosed in fg brackets that must match. The EMACS
editor will help here.

3. The <-- text --> line means “replace with valid “C” statement”.

4. Each line of optional code ends with a “;”.

Logical Statements

The simplest logical statements are formed by variables combined with the logical
operators which are:

S ESSION 00/01 V ERSION 2.2, JANUARY 2001


> Greater Than
< Less Than
== Equals (Note: double == sign)
>= Greater than or equal to
<= Less than or equal to
!= Not equal to

so for a simple example we have:

float x;
<code to set the value of x>
if ( x > 5)
{
printf("The values of x is greater than 5\n");
}

which will print out the message if and only if x > 5.


A few points to note are:

1. The “indentation” is not part of the P ROGRAM, but laying the code out with
“indented” if() will make it much easier to read. The emacs editor will do
most of this for you if you insert a <TAB> before each line.

2. The “equals” (==) operator and the “not-equals” (!=) should not be used with
float or double types since they compare every bit so are highly dependent
on how the number is stored and ultra sensitive to rounding errors. (See more
on this later!)

More on Logical Statements

To form more complex logical statements the logical comparison can be combined
with the three logical operators

|| OR
&& AND
! NOT

Note: The logical AND and OR operators are double characters. There are single
character operators | and & which are the “bitwise operators”. These bitwise oper-
ators are normally used in system or hardware control code and are not considered
in this course. Again using the wrong single bitwise operators when you intended
to use the double logical operator is a common source of program bugs!
These operators are evaluated after the comparison operators, but it is good pro-
gramming practice to put in brackets to make the order of evaluation clear (to you)!
For example a condition of x < 5 OR x > 10 can be written as:

if( (x < 5) || (x > 10))


{
<-- First conditional statement -->;

S ESSION 00/01 V ERSION 2.2, JANUARY 2001


<-- Second conditional statement -->;
.....
}
These two types of operators can be combined to form very complex statements.

int as logical variable

Unlike most other high level languages “C” does not have a special “logical vari-
able”1 . In “C” the int variable is used as the logical, so for example we can write:
int do_more;

do_more = ( x < 4);


if ( do_more )
{
<-- conditional statements -->;
}
The actual value of do more will be
TRUE 1
FALSE 0
Technical aside: The if() statement will take any NON-ZERO value to be TRUE.
This is a feature of the “C” language that should be used with extreme care!

6.3 Double Conditionals


The extended syntax of the if() statement is the very useful if()fgelsefg
if (<logical statement>)
{
<-- First line of optional true code -->;
<-- Second line of optional true code -->;
<-- ....-->;
<-- nth line of optional true code -->;
}
else
{
<-- First line of optional false code -->;
<-- Second line of optional false code -->;
<-- .... -->;
<-- nth line of optional false code -->;
}
When the logical statement is evaluated, if it is TRUE then the code in the first fg is
executed, else the code in the second fg is executed.
The use of the if()fgelsefg gives good “block” structured code that is easy to
read, and thus is more likely to be correct!
1 Most programmers consider this a serious omission in the language

S ESSION 00/01 V ERSION 2.2, JANUARY 2001


6.4 Multiple Conditional
The full syntax of the if() includes the else if() giving the rather complex
structure of:

if (<-- logical statement 1 -->)


{
<-- optional code if logical statement 1 is TRUE -->;
}
else if(<-- logical statement 2 -->)
{
<-- optional code if logical statement 2 is TRUE-- >;
}
.
.
else if{<-- logical statement n -->)
{
<-- optional code if logical statement n is TRUE -->;
}
else
{
<-- optional code is all logical statements are FALSE -->
}

which allow a whole “chain” of logical statement to be “tried-out” with the correct
code executed. The logic of such else if “chains” is very difficult to get right and
even more difficult to D E B UG. If you do need to use this structure then you should
“draw” the structure out on paper first before you try and code it.

6.5 The exit() Function


The exit(); function basically “stops” execution of the program exactly as if the
program had completed. Up to now you have been using this at the end of your
program but it can also be used to conditionally exit the program. The syntax is
simple being

exit(int status);

where status is an integer value that is returned to the operating system. The
function exit(); is defined in the standard library header <stdlib.h> so you
must add #include <stdlib.h> to the top of your program to use this function.
This header file also defines two integer value:

EXIT SUCCESS Pass “success” back to operating system.


EXIT FAILURE Pass “failure” back to operating system.

This is useful for complex programs than interact with the actual system. The
typical use of exit() is to stop your program if an error has occurred, for example:

S ESSION 00/01 V ERSION 2.2, JANUARY 2001


float x,y;
<-- code to calculate value of x -->;
if ( x < 0)
{
printf("Value of x < 0. Fatal Error\n");
exit(EXIT_FAILURE);
}
else
{
y = sqrt(x};
}

which will stop the program (with a sensible message!), if x is negative before it
tries to take the square root of it.
Note: If you do “stop” the program with exit(); as a result of an error always
print out a sensible explanation of what happened. There is nothing worse than a
program that exits with no explanation and does not do what you expected it to.

6.6 Additional Statements


There are two additional conditional constructs in “C” these being:

switch Statement

switch is a complex and very useful dispatch construct that can be used to replace
complex if else() chains. It is mainly used in multi-option programs and is
beyond the scope of this course.
If you are “keen” see Bronson page 172, but I suggest you wait until you have some
experience with the if() construct first!

goto Statement

goto is a unconditional jump to a marked location in a program. This is a dangerous


construct that can lead to highly confusing code. There are two schools of thought
regarding the goto. One says it “should be used only when nothing else works”
and the other says “it should never be used”. Due to the other good conditional
constructs there is no requirement ever to use a goto. See Bronson page 548 if you
really must!

What Next?
You have now completed sufficient “C” to attempt Checkpoint 3.

S ESSION 00/01 V ERSION 2.2, JANUARY 2001

You might also like