Chapter 3 : Conditionals

Chapter 3 : Conditionals

We now get down to some typical program statements. This chapter is concerned with constructs which cause the program to take different paths depending on the values which have been assigned to program variables during the running of the program.

Contents

3.1. If statements

3.1.1. Simple "if" statements

The simplest form of "if" statement causes selected statements to be executed if a certain condition holds at that point in the program.

The condition to be tested appears in parentheses after the word "if", and the statement or statements whose execution is determined by the condition are contained within curly braces. If the condition does not hold, everything up to the next "}" is ignored, and program execution continues after the "}". In this example, if the radius value read in is positive, the program then executes in order the statements

If the value read in is not positive, the statement in the braces following the "if" condition will be ignored, and the program will execute the single statement

If there is a numeric expression in the parentheses, as in

then a value of zero is considered as FALSE, non-zero as TRUE.

3.1.2. "If ... else ..." statements

If the condition does not hold, we may wish to execute some different statements as alternatives to the "if" statements. We add the keyword "else" and the additional statements contained between curly braces.

If the quantity read is positive, the program then executes

If the quantity is zero or negative, the program executes

The careful layout of programs becomes more important as the programs become more structured. Always indent the statements between curly braces more than the lines containing the braces. Some people prefer to put the braces on separate lines as in

Choose a method of laying out programs which you feel happy with, and keep to it. In legal jargon, I would say that the closing curly brace must line up with the first visible character on the line containing the opening curly brace.

3.1.3. Further alternatives

We can add further alternatives to an "if" statement if we require.

The tests in the if statements are executed exactly in the order in which they are encountered. The first test here is "radius > 100"; if this is false, the second test if executed, testing whether "radius > 10", so that this is effectively the test "radius <= 100 && radius > 10", since we know that the first test is false.

3.1.4. Possible conditions (logical expressions)

We looked at the format of conditions in chapter 2, when we were discussing expressions in general.

It is generally bad practice to compare two float values for equality or inequality. Because of rounding errors, the results of a floating expression may not be exactly what you think. The exception to this rule is to read in a float value using scanf and immediately compare it with zero, for example.

Lazy operators

The AND and OR operators above are lazy. The word "lazy" has a proper meaning in the compilation of programs. The "and" and "or" logical operators ("&&" and "||") are lazy, i.e. are evaluated from left-to-right, and stop as soon as the result is determined.

The "and" operator stops as soon as a false expression is encountered; the "or" stops as soon as a true expression is encountered.

In C you can safely write

since the sqrt will not evaluate unless the first condition holds.

Remember all the points on conditions from chapter 2, in particular the interpretation of the value zero as FALSE, and non-zero as TRUE; the danger of using assignment instead of equality; and the danger of testing equality between "float"s. operators.

3.1.5. The comma operator

You may find the comma operator useful when the test you wish to perform involves several calculations, as in

To make the program more readable, you may choose to lay this out on more lines as

The first two statements could be written before the "if" if you prefer, so that we could also write

You may not find the comma operator helpful at first. There are many philosophical arguments about programs and their structure, and the argument in favour of the comma here is that all the calculations involved in the test should be grouped together within the "if" condition.

3.1.6. Nesting "if" statements

Your "if" statements can be nested to your heart's content if that is what the program logic requires.

3.1.7. Ambiguity

We have specified above that you must always use curly braces after an "if" condition and after the "else". The C official definition states that the curly braces are essential only if there is more than one statement to be executed as a result of the condition. Many commercial users of C insist, as we do, that the curly braces should always be there.

If you don't use curly braces, the following is ambiguous.

The above could mean either

or

These two have quite different effects. In the case when, for example, "radius > 0" and not "result > 0", the first will execute "yyy", the second will have no effect. If we have "radius <= 0" (the first condition is FALSE) and "result > 0", the first example will have no effect, while the second would execute "yyy". The two are thus quite different in their effect.

It is a good principle always to use curly braces, and to put a comment after any closing curly brace which is not close to its opening partner. An example might be

Our rule (enforced by the Ceilidh marking system) will be that a closing curly brace must have a comment if it is more than 10 lines after its opening curly brace. This ensures that you see a comment on the computer terminal screen if the complete "if" statement is unlikely to fit onto one screenful of information.

3.2. Switch statements

The "if" statement essentially gives a choice between two alternatives. We may sometimes need a choice between a larger number of possibilities. The "switch" construct illustrated below allows for any number of different actions to be taken dependent of the value of an integer calculation.

3.2.1. Switch example

The value after the word "case" must be a constant, you could not put

where "j" is an "int" variable. You must put either an explicit constant (the numeric value 7), or a #define constant where you have declared for example

Two "case" labels can be adjacent. In this case, the two specified values will cause the same code to be executed.

Don't forget the "break;" statements if you need them. You will normally want control to leave the "switch" statement at the end of each separate "case".

The default: entry is optional, but will most often be included.

The value in the "switch" parentheses must be an integer variable or expression. It cannot be a "float" value.

3.2.2. Character switch example

Note the printing of the single character, and the quotes round it. The quotes are written \" within the format string.

Note again the careful indentation, and the comment after the closing curly brace.

Think also of omitting the break statements on the rare occasions when you wish to cause code to follow through as in this example.

In this case,

3.2.3. Notes

The expression in brackets after "switch" must deliver an integral value, not a float or double. Integers, characters and long integers are permitted.

All the time as we learn new constructs, programs become more complex, and the neat layout of programs becomes more important. Our automatic marking system will check your layout.

Coursework exercise marking

The exercises in this unit are marked partly on dynamic correctness, partly on typographic layout, and sometimes on Features. For dynamic correctness and typographic layout, earlier comments apply (see the end of unit 2 notes and the program layout section above).

The features mark is problem specific, and concerns the items which a teacher would look for by eye if marking your programs by hand. For example, if the problem involves converting centimetres to inches, the conversion factor 2.54 should appear as a single global constant in a

, it should NOT appear more than once, it should NOT appear in the program. If you are converting minutes to hours, the constant 60 should appear only once, as a global constant, and it is bad practice to use the constant 59. Always use

rather than

when the value which represents the factor which concerns us (the number of minutes in an hour) is 60, not 59.

Copyright Eric Foxley 1996


Notes converted from troff to HTML by an Eric Foxley shell script, email errors to me!