Decisions 


C Programming Tutorial 

Go to the Table of Contents

 

Testing and Branching. Making conditions.

Suppose that a fictional traveller, some character in a book like this one, came to the end of a straight, unfinished road and waited there for the author to decide where the road would lead. The author might decide a number of things about this road and its traveller:

  • The road will carry on in a straight line. If the traveller is thirsty he will stop for a drink before continuing.
  • The road will fork and the traveller will have to decide whether to take the left branch or the right branch.
  • The road might have a crossroads or a meeting point where many roads come together. Again the traveller has to decide which way to go.

We are often faced with this dilemma: a situation in which a decision has to be made. Up to now the simple example programs in this book have not had any choice about the way in which they progressed. They have all followed narrow paths without any choice about which way they were going. This is a very limited way of expressing ideas though: the ability to make decisions and to choose different options is very useful in programming. For instance, one might want to implement the following ideas in different programs:

  • If the user hits the jackpot, write some message to say so. "You've won the game!"
  • If a bank balance is positive then print C for credit otherwise print D for debit.
  • If the user has typed in one of five things then do something special for each special case, otherwise do something else.

These choices are actually just the same choices that the traveller had to make on his undecided path, thinly disguised. In the first case there is a simple choice: a do of don't choice. The second case gives two choices: do thing 1 or thing 2. The final choice has several possibilities.

C offers four ways of making decisions like the ones above. They are listed here below. The method which is numbered 2b was encountered in connection with the C preprocessor; its purpose is very similar to 2a.

1: if (something_is_true)
 {
 /* do something */
 }

2a: if (something_is_true)
 {
 /* do one thing */
 }
 else
 {
 /* do something else */
 }

2b: ? (something_is_true) :

 /* do one thing */
 :

 /* do something else */


3: switch (choice)

 {
 case first_possibility : /* do something */
 case second_possibility : /* do something */

 ....
 }