More on <I>if</I>


Let's talk a little bit more about how if statements work. How do they figure out if a statement is TRUE or if it is FALSE?

The answer is simple: Anything that simplifies to 0 is false. Everything else is true. What does this mean? Well, it means that you don't have to stick to comparisons like "is a less than 4?" in your if statements -- you can have if statements that simply have a variable; if the variable is zero, the result is the same as a FALSE, but if not, it's a TRUE. Take a look at the following example:

void main(void)
{
  int a;
  int b;

  a = 0;  / Same as FALSE
  b = 1;  / Same as TRUE

  if (a)
    a = 500;

  if (b)
    b = 500;
}

Look at how the if is without any operators. All it consists of is a single variable! While this may feel a little strange, think about how your programs really work. Take this statement, for example:

if (a > 5)

In that piece of code, you have the statement "a > 5". When the program runs, this statement is ran before the if statement. If a was set to 6, the statement would simplify to TRUE, which is the same as 1. So, the new, simplified statement is:

if (1)

Which, because it's non-zero, is a TRUE, and the statement following it runs.


Table of Contents

The Big Picture | Comments | Variables | More on Variables
Variable Operations | Making Choices | More on if | Using else
Using switch | The while Loop | The do..while Loop | Constants
The for Loop | More on the for Loop | Exercises