Node:Decisions, Next:, Previous:Pointers, Up:Top



Decisions

Testing and Branching. Making conditions.

Until now, our code examples have been linear: control has flowed in one direction from start to finish. In this chapter, we will examine ways to enable code to make decisions and to choose among options. You will learn how to program code that will function in situations similar to the following:

In the first case there is a simple "do or don't" choice. In the second case, there are two choices. The final case contains several possibilities.

C offers four main ways of coding decisions like the ones above. They are listed below.


if...

if (condition)
{
  do something
}

if...else...

if (condition)
{
  do something
}
else
{
  do something else
}

...?...:...

(condition) ? do something : do something else;

switch

switch (condition)
{
  case first case : do first thing
  case second case : do second thing
  case third case : do third thing
}