3 minute briefing on if

What are all those numbers and variables good for when all you need is to make a decision? What I am going to write about is called “flow control” because the “flow” of the program to do one or the other thing is controlled, and one of the many ways of doing that is by using the command “if”. Technically “if” assesses the truth of a statement, and either does something or it doesn’t. To do so, if uses a couple of comparisons operators like bigger > or smaller <. To come up with a stupid example imagine you want to pay a bonus to your employee once more than say 100 donuts were sold:

if(donuts>100)
     payment=payment+bonus;

Simply put if the statement within the () is “true” the next line gets executed, otherwise skipped. If you need to make a couple of commands dependent on your if, use {} and everything within those {} (called scope) gets executed:

if(donuts>100){
     payment=payment+bonus;
     printf("You received a bonus!");
}

The printf in there just puts text to the command line. There are two other important comparators besides < and > which are == (equal) and != (unequal). The thing that will drive you nuts is this double equal sign to indicate a comparison, opposed to the single equal sign which indicates that what is left of it is assigned to what is to the right.

One last thing is the “else”:

if(donuts>100){
     payment=payment+bonus;
     printf("You received a bonus!");
} else {
     printf("Work harder!");
}

Which does nothing else than to allow you to execute something else in case the condition within the if is not met.

Cheers Arend

Leave a Reply