Sams Teach Yourself C in 21 Days

(singke) #1
The Pieces of a C Program: Statements, Expressions, and Operators 73

4


TheifStatement ..................................................................................................


Relational operators are used mainly to construct the relational expressions used in if
andwhilestatements, covered in detail on Day 6, “Basic Program Control.” For now,
you will learn the basics of the ifstatement to show how relational operators are used to
make program control statements.
You might be wondering what a program control statement is. Statements in a C program
normally execute from top to bottom, in the same order as they appear in your source
code file. A program control statement modifies the order of statement execution.
Program control statements can cause other program statements to execute multiple times
or to not execute at all, depending on the circumstances. The ifstatement is one of C’s
program control statements. Others, such as doandwhile, are covered on Day 6.
In its basic form, the ifstatement evaluates an expression and directs program execution
depending on the result of that evaluation. The form of an ifstatement is as follows:
if (expression)
{
statement;
}
Ifexpressionevaluates to true,statementis executed. If expressionevaluates to false,
statementis not executed. In either case, execution then passes to whatever code fol-
lows the ifstatement. You can say that execution of statementdepends on the result of
expression. Note that both the line if (expression)and the line statement;are con-
sidered to make up the complete ifstatement; they are not separate statements.
Anifstatement can control the execution of multiple statements through the use of a
compound statement, or block. As defined earlier in today’s lesson, a block is a group of
two or more statements enclosed in braces. A block can be used anywhere a single state-
ment can be used. Therefore, you could write an ifstatement as follows:
if (expression)
{
statement1;
statement2;
/* additional code goes here */
statementn;
}

07 448201x-CH04 8/13/02 11:15 AM Page 73

Free download pdf