Minggu, 05 September 2010

The If Statement in C language

Relational operators are used mainly to construct the relational expressions used in if and while statements, covered in detail on Day 6, "Basic Program Control." For now, I'll explain the basics of the if statement 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 if statement is one of C's program control statements. Others, such as do and while, are covered on Day 6.

In its basic form, the if statement evaluates an expression and directs program execution depending on the result of that evaluation. The form of an if statement is as follows:

if (expression)
    statement;
If expression evaluates to true, statement is executed. If expression evaluates to false, statement is not executed. In either case, execution then passes to whatever code follows the if statement. You could say that execution of statement depends on the result of expression. Note that both the line if (expression) and the line statement; are considered to comprise the complete if statement; they are not separate statements.
An if statement can control the execution of multiple statements through the use of a compound statement, or block. As defined earlier in this chapter, a block is a group of two or more statements enclosed in braces. A block can be used anywhere a single statement can be used. Therefore, you could write an if statement as follows:

if (expression)
{
    statement1;
    statement2;
    /* additional code goes here */
    statementn;
}


DO remember that if you program too much in one day, you'll get C sick. DO indent statements within a block to make them easier to read. This includes the statements within a block in an if statement.
DON'T make the mistake of putting a semicolon at the end of an if statement. An if statement should end with the conditional statement that follows it. In the following, statement1 executes whether or not x equals 2, because each line is evaluated as a separate statement, not together as intended:

if( x == 2);          /* semicolon does not belong!  */
statement1;
In your programming, you will find that if statements are used most often with relational expressions; in other words, "Execute the following statement(s) only if such-and-such a condition is true." Here's an example:

if (x > y)
    y = x;

Tidak ada komentar:

Posting Komentar