The if Statement

Summary: The body of an if statement executes when its test expression is true.

An if statement consists of the if keyword followed by a test expression in parentheses and a second statement. The second statement is executed if the test expression is true, or skipped if the expression is false.

The IFF.C program contains a simple if test. It prints a prompt and waits for you to press a key.

/* IFF.C: Demonstrate if statement. */

#include <stdio.h>

main()

{

char ch;

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

ch = getchar();

if( ch == 'b' )

printf( "Beep!\n" );

}

In the IFF.C program, the statement

ch = getchar();

calls the getchar library function to get a keystroke from the keyboard and then assigns the result to the variable ch. If you press the B key and then press ENTER, the program prints

Beep!

(To simplify the code, IFF.C tests only for a lowercase b character. A program would normally use a library function such as tolower to test for both upper and lowercase.)

Figure 3.4 illustrates the parts of the if statement in the IFF.C program.

The test expression of the if statement

ch == 'b'

Summary: The equality operator (==) tests if values are equal.

is true when the variable ch equals the letter “b.” In C the equality operator (==) tests if two values are equal. (For a discussion of operators, see Chapter 6.)

The body of the if statement in IFF.C happens to be a single statement, but the body can also be a statement block, as in the following fragment:

if( ch == 'b' )

{

printf( "Beep!\n" );

printf( "You pressed the 'b' key\n" );

}

You can also nest if statements, as shown below:

if( ch == 'b' )

{

printf( "Beep!\n" );

beep_count = beepcount + 1;

if( beep_count > 10 )

{

printf( "More than 10 beeps...\n" );

if( beep_count > 100 )

printf( "Don't wear out the 'b' key!\n" );

}

}

The code nests three if statements. The first if tests whether ch equals the letter “b”; the second tests whether the variable beep_count is greater than 10. The third tests whether beep_count exceeds 100.