Monday, January 26, 2009

If; relational operators; compound statements

The basic conditional-testing statement in C is the if statement:
c = getchar( );
if( c == '?' )
printf("why did you type a question mark?\n");
The simplest form of if is
if (expression) statement
The condition to be tested is any expression enclosed in parentheses. It is followed by a statement. The expression is evaluated, and if its value is non-zero, the statement is executed. There's an optional else clause, to be described soon.
The character sequence `==' is one of the relational operators in C; here is the complete set:
== equal to (.EQ. to Fortraners)
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
The value of ``expression relation expression'' is 1 if the relation is true, and 0 if false. Don't forget that the equality test is `=='; a single `=' causes an assignment, not a test, and invariably leads to disaster.
Tests can be combined with the operators `&&' (AND), `||' (OR), and `!' (NOT). For example, we can test whether a character is blank or tab or newline with
if( c==' ' || c=='\t' || c=='\n' ) ...
C guarantees that `&&' and `||' are evaluated left to right -- we shall soon see cases where this matters.
One of the nice things about C is that the statement part of an if can be made arbitrarily complicated by enclosing a set of statements in {}. As a simple example, suppose we want to ensure that a is bigger than b, as part of a sort routine. The interchange of a and b takes three statements in C, grouped together by {}:
if (a < b) {
t = a;
a = b;
b = t;
}
As a general rule in C, anywhere you can use a simple statement, you can use any compound statement, which is just a number of simple or compound ones enclosed in {}. There is no semicolon after the } of a compound statement, but there is a semicolon after the last non-compound statement inside the {}.
The ability to replace single statements by complex ones at will is one feature that makes C much more pleasant to use than Fortran. Logic (like the exchange in the previous example) which would require several GOTO's and labels in Fortran can and should be done in C without any, using compound statements.

No comments:

Post a Comment