What In The Hell Are Conditionals

GOTO All What In The Hell Articles

A conditional is a mechanism for altering the control flow of a program based on the result of a test.  That is a very technical and complicated description of something that is very simple in practice.  Let’s look at a small example before continuing.

if temperature > 80:
  run_air_conditioning()

All humans are used to dealing with conditional statements, in fact we probably compute thousands of conditionals every day without even thinking about them.  They’re so in-grained in our thinking that I didn’t even have to explain the example above, you just got it.

The most basic form of conditional, which is present in almost every language, is if/else.  Each language has slightly different syntax which we’ll get to in a moment, first let’s look at some psudo-code that describes the basic workings of if/else.

if test:
  do_if_test_is_true()
else:
  do_if_test_is_false()

When our programming language comes across this block of code it will first evaluate test.  If the evaluation of test equals true, the do_if_test_is_true() function will be called.  If the evaluation of test equals false, the do_if_test_is_false() function is called.

Note that if test evaluates to true the do_if_test_is_false() function is never called.  This behavior is called branching and a popular way of specifying control flow in a program.

if predicate:
  consequent
else:
  alternate

These are some common terms that refer to the parts of an if/else.  Predicate refers to the expression or statement that is to be tested.  Consequent refers to the action to be taken if the predicate is equal to true.  Alternate refers to the action to be taken if the predicate is equal to false.

You’ve already seen examples from Python (even our psudo-code examples were valid Python), here’s some examples from other languages of if/else.

Javascript

if (2 > 1) 1
//>>> 1

if (1 > 2) {
  1;}
else {
  2;}
//>>> 2

Scheme

(if (> 2 1) 1)
;>>> 1

(if (> 1 2)
    1
    2)
;>>> 2

 

Else If

Another common pattern is if/else if/else.  This pattern is equivalent to chaining if/else expressions together.  Here’s some psudo-code of an if/else if/else in Python and then a diagram of how it is executed.

if temp > 80:
  run_ac()
elif temp < 60:
  run_heat()
else:
  do_nothing()

As you can see, Python first checks if the temperature is greater than 80.  If the temperature is greater than 80, Python will call run_ac() and ignore the rest of the code.  If the temperature is less than 80 it will call the elif branch and check if the temperature is less than 60.  If the temperature is less than 60, Python will call run_heat() and if the temperature is between 60 and 80 Python will call do_nothing().

Instead of using the keyword elif, we could have written our Python code a different way that emphasizes the nesting.

if temp > 80:
  run_ac()
else:
  if temp < 60:
    run_heat()
  else:
    do_nothing()

Writing our program this way makes it clear that each ‘else if’ branch is just another if/else. However keywords like elif exist for a reason and if you are thinking about nesting your if/else expressions, don’t.

You’ve seen elif in Python, now I’ll show you how some other languages handle it.

 

Functions in Other Languages

Javascript

if (temp > 80) {
  1;}
else if (temp < 60) {
  2;}
else {
  3;}

Scheme

(cond ((> temp 80) (run-ac))
      ((< temp 60) (run-heat))
      (else (do-nothing)))

As you can see the syntax can vary quite considerably between languages.  However the fundamental concept of the if/else is the same in most programming languages.

 

Switch

Switch is another form of conditional.  Using the if/else if/else model above is sufficient for a small number of possible conditions.  However as the number of conditions grows the limitations of if/else if/else start to show.

The main problem is that each condition must be checked every time the conditional is evaluated.  If there were 100 conditions each one would have to be checked until one of them was true.  If the condition that returns true is at the end of that list, it could take a lot of time to find it.

Switch statements are usually found in lower-level languages, however I’ll show you how to implement them in higher-level languages as well (should you need them).  A switch in a lower-level language is often implemented as a branch table (or jump table) and can only be done on integers.

Switch in C:

switch(expression_returning_int) {
  case 1:
    printf("Expression returned 1.\n");
    break;
  case 2:
    printf("Expression returned 2.\n);
    /* since there is no break; here it will 'fall through' to default. */
  default:
    printf("Expression returned greater than 1.\n");
    break;
}

In the example above the expression expression_returning_int will be evaluated (it must return an integer).  The value of the expression will then be used as an index into the branch table.  Control is then transfered to the branch referred to by the expression or the default branch (if supplied).

In the example above a break statement was not supplied for the case 2.  If expression_returning_int equals 2 it will print:

Expression returned 2.
Expression returned greater than 1.

The break statement normally stops the execution of that branch.  When it is not present the control flow “falls through” to the next branch, and the next, and the next until it hits a break statement or the end of the switch.  This is a common characteristic of switch statements, however it is not universal.  A switch would still be a switch even if it didn’t allow execution to fall through branches.

 

Switch in Higher-Level Languages

Many high level languages do not provide a switch statement.  However this is rarely a problem as they often do supply data structures which let us represent one easily.

A switch on integers can be done as an array lookup, if you want to learn more about arrays first go to What In The Hell Are Arrays.

If we think about the switch statement above it maps out a little bit like this…

You’ll notice a problem with the above representation.  Where is the ‘default’ branch?  The default branch would be executed by array_lookup if it did not find a value in the array.  The implementation of this will be left as an exercise to the reader as the specifics vary from language to language.

Similarly a switch on strings, or other hash-able values, can be done as a hash lookup.  If you want to learn more about hash tables go to What In The Hell Are Hash Tables.

 

Links

GOTO Table of Contents

Advertisements