Back to A Brief Guide to C
If / Else
01 if (x == y) { /* executes if x is equal to y */
x *= 3;
printf("Eat Chicken.\n");
04 }
05 else if (x == z) /* executes if x is not equal to y, but is equal to z */
printf("Don't eat the chicken.\n");
07 else { /* executes if x is not equal to z, but is only called if x is not equal to y */
x = y;
printf("Don't eat, nor not eat, the chicken.\n");
}
12 if (y > x)
printf("Put the chicken down and step away from the bucket.\n");
Welcome to the if statement. It has several ways of being written, all of which can
be seen in the code sample above.
- line 01: If the arguement within the paren's evaluates to true (in
C, this is any value other than '0'), the statements within the curly braces are executed;
otherwise, it skips to after the closing curly brace (on line 04). As always, the perverse
among you may put the opening curly brace on a separate line rather than on the same line
as the if().
- line 05: The else statement is executed only if the if it is paired with (on line 01)
fails. In this example, the else statement would only execute if x was not
equal to y. On this line, it is paired with another if. Don't be fooled. This way
of writing is no different to the compiler than doing the following:
else {
if (x == z) {
printf("Don't eat the chicken.\n");
}
}
It's just a little more compact & clean the way I've written it in the first code sample,
and it's the way you'll most often see this combination written.
The other different thing about this line is that there isn't an opening & closing
curly brace. In this case, the compiler only executes up to the end of the statement (that
is, up until the ';') if the arguement within the paren's evaluates to true.
- line 07: An else by itself will execute only if the previous 'if' failed. Therefore,
this else is looking at the if() on line 05 to see if it executed or not.
- line 12: An if without an else is legal as well (you'll also notice this is the without-
curly brace variety of if())
Switches
01 switch (y) {
02 case 2:
x++;
04 break;
05 case 3: case 4:
x += 2;
z = 1;
break;
07 default:
x = 0;
break;
}
The switch statement is a good way to do a lot of tests on a single variable without writing
a whole lot of
if and
else if.
- line 01: The beginning of the statement. The variable mentioned within the paren's is the
one which is compared in the case statements.
- line 02: A case statement is analogous to an if statement; in this case, you could replace
the switch up to this point as if (y == 2) {.... If the variable is equal to the
value given to the case, the statements below the case are executed. If it is not equal, the
statments are skipped.
- line 04: If you want to skip to the end of the switch after you find a match, you need to
use a break. If you don't, the program will execute all of the statements after
the one that matches. In this case, if the breaks were removed and y had the value of '4', lines
6, 7, and 10 would execute. With the breaks, only line 6 and 7 would execute if y had '4'.
- line 07: The default case is executed only if all of the case statements failed.
Even if you think it's impossible for the all cases you have defined to fail, it's a good idea
to include a default statement (probably with an error message).
While Loops
These come in two varieties, slightly different from each other:
01 while (x > 3) {
02 x /= 2;
printf ("foo.");
}
06 do {
x /= 2;
printf ("bar.");
09 } while (x > 3);
For Loops
These are a safer replacement for the while loop 75% of the time.
01 for (x = 0; x < 4; x++) {
printf ("%d\n", x); /* this prints the current value of x to the console */
y *= x;
}
- line 01: The for statement provides fields to initialize, test, and update a control variable.
The first statement within the parentheses intializes the control variable. The variable must
be declared, of course, but its value does not matter as it is set in this statement. The next
statement is the test. It performs the test before any statements within the for's curly braces
are executed. The last statement is the update, which advances the control variable. The
for executes these in this order:
for (initialize; test; advance) { statements }
- Initialize
- Test. If failed, exit loop (that is, jump to the closing curly brace)
- Execute Statements
- Execute update
- Test...
Note: You don't have to use the initialize, test, or advance if you don't want to. This is
useful for using a for loop without initializing the control variable, or where
the control variable update is handled within the loop.
Loop Control Statements
There are those who believe that the following are bad to use, since they can be accomplished
through careful construction of loops. My opinion is that they should be used, sparingly, only
where it would be very difficult to construct a loop to catch the condition. The code examples
don't meet this criteria, but I've included them just for examples of use, not good programming
style.
- break
for (; x > 1; x -= 2) { /* note the uninitialized control variable */
y += x;
if (y > 180)
break;
}
In this case, I want the loop to exit if x is less than 1 or y is greater than 180.
- continue
for (x = 0; x < 15; x++) {
if (x % 2) /* that is, if x is odd (an odd number modulo 2 gives 1, or true) */
continue;
y *= x;
}
This statement skips the remaining code in the loop, but does not exit the loop. So in this
case, the y *= x; statement is only executed when x % 2 gives '0' (that is,
when the if fails and the continue is not executed).
Using Logical Operators to Make More Complex Loops
Up until now, I've only shown loop control with one
variable. Using the
logical operators
talked about in
C: Operators, you can control your loops with as many arguments as
you'd like. For instance,
while ((x == 0) && (y < 10)) { /* loop while x is 0 AND y is less than ten */
y++;
z *= y;
if (((y == 3) || (y == 7)) && (z > 20)) /* if y is 3 OR 7 AND z is greater than 20 */
x++;
}