4.2. if ... else

A second form of if statement exists which allows you to also specify a block of code to execute if the test expression is false. This is known as an if ... else statement and is formed by placing the reserved word else and another block of code after the usual if statment. You program will execute one of the two blocks of code based on the test condition after the if. Here's what it looks like:

Example 4-2. cows2.c

  int cows = 0;

  if (cows > 1)
      printf("We have cows\n");
      printf("%d cows to be precise\n", cows);
      if (cows == 0)
        printf("We have no cows at all\n");
        printf("We have only one cow\n");

  if (cows > 10)
    printf("Maybe too many cows.\n");

  return 0;

You should be able to guess the output by now:

ciaran@pooh:~/book$ ./cows2
We have no cows at all
In the last example there was an if .. else statement inside another if .. else statement. This is perfectly legal in C and is quite common. There is another form of branching you can use but it's a little more complex so we'll leave it to to end of the chapter.