The else Clause

Summary: An else clause can follow an if statement.

The else keyword is used with if to form an either–or construct that executes one statement when an expression is true and another when it's false. The ELSE.C program demonstrates else by adding an else clause to the code from IFF.C. It prints Beep! if you type “b” and press ENTER, or it prints Bye bye if you type any other character. (The getchar library routine, used in this and other examples, waits for you to press ENTER before it ends the input, so remember to press ENTER after typing the chosen character.

/* ELSE.C: Demonstrate else clause. */

#include <stdio.h>

main()

{

char ch;

printf( "Type b and press Enter to print Beep.\n" );

ch = getchar();

if( ch == 'b' )

printf( "Beep!\n" );

else

printf( "Bye bye\n" );

}

Summary: To create an else–if construct, place an if statement after an else.

The C language has no “elseif” keyword, but it's easy to create the same effect, because the statement that follows else can be any C statement—including another if statement. The ELSE1.C program uses if and else to test three conditions. It prints Choice 1 when you type 1, it prints Choice 2 when you type 2, or it prints Bye bye when you type any other character. (Again, remember to press ENTER after typing your choice.)

/* ELSE1.C: Demonstrate else-if construct. */

#include <stdio.h>

main()

{

char ch;

printf( "Type 1 for Choice 1, type 2 for Choice 2.\n" );

ch = getchar();

if( ch == '1' )

printf( "Choice 1\n" );

else

if( ch == '2' )

printf( "Choice 2\n" );

else

printf( "Bye bye\n" );

}

The else keyword is tied to the closest preceding if that's not already matched by an else. Keep this rule in mind when creating nested if-else constructs. (For more information, see “Mismatching if and else Statements”.)