March, 1998 Learning to C

Part 6: Conditionals

In a C program sometimes it is required to compare one or two variables. This allows you to create conditional statements, statements that only execute when a certain condition or set of conditions is met. Conditional comparisons are very important in programming since they control the program flow. They are what allow you to check and compare items, to execute specific statements only at certain times or specific occasions. They also allow you to program the computer to almost think or make decisions based on the comparison of the values of specific variables.

The first keyword in C programming used for conditional comparisons is "if." It is used in C similar to the way it is used in English. If something is true, then do something specific. An example in pseudo-code would be like this:

if (your car is broken) fix your car

The items that are checked are within parenthesis in order to set them aside from the rest of the statement. The computer verifies that the condition or conditions within the parenthesis are true, then it will execute the statment which follows the comparison. A variety of equality and conditional operators are used with conditional comparisons. Many you should recognize from high-school math classes like the less than, greater than and equality signs. Others are specific to the C programming language, like && which is used to mean "and" when you want to make sure both conditions on the left and right are true, or || which is used to mean "or" when you want to check if at least one of the conditions is true.

It is usually easiest to learn conditional comparisons by example so here is a simple example in C code. These examples are using pre-defined values for x and y so are not very useful except as examples. In a future article you will learn how to read input in from the user which could give the variables values that are not already known by the program.

/* if.c 1.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 2, y = 1;

     if ( x > y )
     {
         x = y;
     }
}

The if statement compares the x and y variables and if the value of x is greater than the value of y, it will execute the statement that follows. The if statement can only execute one statement unless you use the open and close braces for a compound statement. Using them when they are not needed, like in this example, will not hurt the program and will not even add any extra size to the finished file, and if you decide to add another statement into the braces you don't have to worry about forgetting them and causing a run-time error in your program. This is called pre-emptive debugging. It allows you to prevent possible errors by over compensating. It doesn't take much effort to add the braces and using them also makes the program code easier to read.

The white space, or extra spacing and lines, in the if statement is also not necessary, but assists in the readability of the program code. It could just as easily have been written without the braces and without the new lines like this:

/* if.c 2.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 2, y = 1;

     if ( x > y ) x = y;
}

However, if you had a more complex if statement, or ever needed to make adjustments to it, writing it as in the first example would facilitate this as well as make it easier to debug any errors.

If x was assigned the value of 1 and y was assigned the value of 2, then the comparison would have been false and the if statement would not execute the statement that follows the comparison. If you wanted to do a different statement if the comparison was false, you could create a second if statement that checks for that condition like in this example:

/* if.c 3.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 2, y = 1;

     if ( x > y )
         x = y;
     if ( x <= y)
         y = x;
}

An easier way to do this would be to use the "else" keyword. This allows you to create a single if statement that does one comparision then executes one set of statements if the comparison is true, otherwise it executes a different set of statements. Performing one comparison is faster and see how concise the use of the else keyword is compared to the last example:

/* if.c 4.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 2, y = 1;

     if ( x > y )
         x = y;
     else
         y = x;
}

You can nest if-else statements within one another, but should always be sure to use braces and comments so you know which else goes with which if. Compound comparisons are simple and use the "and" and "or" operators mentioned previously. Here is an example of a compound comparison using the or operator:

/* if.c 5.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 2, y = 1;

     if ( ( x > y ) || ( y < x ) )
         x = y;
}

This compound comparision checks to see if the value of the x variable is greater than or less than the value of the y variable. If the variables are not equal, then it assigns the value of y to x. While this compound comparison here is somewhat redundant, checking the same variables twice, it could just easily be used to check an unlimited number of variables. Notice that each comparison is surrounded by parenthesis, as well as a pair surrounding all the comparisons. While the outside parenthesis are required, the others are only required based on the standard order of operation. Greater-than and less-than comparisons takes precedence over the or comparison, so while they are not required, it does no harm to have them and it makes reading the comparisons much easier.

An easier method to make the same comparison as the previous program example is to use the ! symbol which is called the "not" operator. When used in a comparison it inverts the value of the comparison so if the comparison is true, setting it to !true means it is false. Here is the same example using this operator:

/* if.c 6.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 2, y = 1;

     if ( x != y )
         x = y;
}

What this if statement is saying is that if the value of the x variable does not equal the value of y then assign the value of y to the x variable. The following information is very important because this is one of the most common errors in C programming. When assigning the value of a variable to another variable you use the assignment opperator, one equal sign. When comparing two variables to see if they are equal to one another, you must use two equal signs. Here is an example:

/* if.c 7.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 2, y = 1;

     if ( x == y )
         x = x + 1;
}

If you make a mistake in your comparison and use only one equal sign it can be very hard to detect. The program will still compile just fine, and may even run, but it won't run properly and the cause could be hard to impossible to find. The reason why is that in the C programming language, the value of false is zero, and the value of true is any value that is not zero. If a comparison uses a single equal sign, the value of the second variable is assigned to the fist variable, and if the value is not zero then the comparison is given a non-zero, or true result. Here is an example:

/* if.c 8.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 2, y = 1;

     if ( x = y )
         x = x + 1;
}

Since there is only one equal sign used in the if statement comparison, the value of y, 1, is assigned to the variable x instead of comparing the two variables. Since the value is not zero, the if statement will always be true, which is not the correct results you would expect since the value of the x and y variables are not the same before the comparison.

For very simple comparisons and assignments, C has a shortcut operator, the question mark. It is used as quick comparisons and assignments. Here is an example:

/* ternary.c 1.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 1, y = 2;
     int z;

     z = ( x > y ) ? x : y;
}

What this means is if the value of x is greater than the value of y, the expression x is used, else y is used and the expression which is used is then assigned to the value of x with the assignment operator, the equal sign. While this greatly speeds up typing and execution of the program, it can be hard to read and should only be used for very simple comparisons. You may never use it but should know what it means in order to read the C programming code of other people.

There is another shortcut used when comparing a value to many other constant values. This is the "switch" statement. This simple statement allows you to easily and quickly compare one value against a wide range of constant values. Here is an example:

/* switch.c 1.0 (03/28/98) */
int main(int argc, char *argv[])
{
     int x = 3;

     switch (x)
     {
         case 1 : x = x + 3;
             break;
         case 2 : x = x + 2;
             break;
         case 3 : x = x + 1;
             break;
         case 4 : /* NOP*/
             break;
         case 5 :
         case 6 : x = 0;
             break;
         default : x = 5;
     }
}

The values compared in a switch statement must be constants. In this example it compares the value of x to the numbers 1 through 6. Since the variable x, which is the variable being compared, is changed within the switch statement, the break statement is used to break out of the comparisons. Otherwise when x is compared and found to match 3, it is incremented to 4, then it is compared to 4 and that operation will be executed also. The break statement also speeds execution, preventing the following comparisons.

In the situation where x would be equal to 4, if you desire nothing to happen at all, a break statement is used alone. This example has the comment /* NOP */ so that anyone who reads the program can see that you want no operation to be performed in this case. If you want one set of statements to be executed when the value matches 2 or more comparisons, you list the case statements without putting the break statement, like case 5 and case 6 in this example. The default option is used if you want statements executed if none of the comparisons match, similar to the else in an if-else statement.

Conditional comparisons control the flow of the program, allowing it to make decisions and perform statements only when certain conditions are met. Like everything in C programming, the comparison statements become easier to understand with practice, and always be sure to use the double equal symbol when making an equality comparison and a single equal sign for a value assignment.