Friday, July 20, 2012

CPro1 Lecture: Statements, Expressions and Operators


4
Statements, Expressions and Operators
OBJECTIVE
C programs consist of statements, and most statements are composed of expressions and operators.  You need an understanding of these three topics to be able to write C programs.  In this chapter, you learn
·  What a statement is.
·  What an expression is.
·  C’s mathematical, relational, and logical operators.
·  What operator precedence is.
·  The if statement.
Statements
A statement is a complete direction instructing the computer to carry out some task.  In C, statements are usually written one per line, although some statements span multiple lines.  C statements always end with a semicolon (except for preprocessor directives such as #define and #include.  For example,
x = 2 +3;
is an assignment statement.  It instructs the computer to add 2 to 3 and assign the result to the variable x.
Statements and Whitespace
The term whitespace refers to spaces, tabs, and blank lines in your source code.  The C compiler is not sensitive to whitespace.  When the compiler is reading a statement in your source code, it looks for the characters in the statement and for the terminating semicolon, but it ignores the whitespace.  Thus, the statement x=2+3; is exactly equivalent to
x  =  2  +  3;
and it is also equivalent to
x        =
2
+
                 3;
Compound Statements
A compound statement, also called a block, is a group of two or more C statements enclosed in braces.  Here’s an example of a block:
{
  printf(“Hello, “);
  printf(“World!”);
}
DO / DON’T
DO       stay consistent with how you use whitespace in statements.
DO       put block braces on their own line.  This makes the code easier to read.
DO       line up block braces so that it is easy to find the beginning and end of a block.
DON’T  spread a single statement across multiple lines if there us no need.  Try to keep it on one line.
Expressions
In C, an expression is anything that evaluates to a numeric value.  C expressions come in all levels of complexity.
Simple Expressions
The simplest C expression consists of a single item:  a simple variable, literal constant, or symbolic constant.  Here are four expressions:
PI             /* a symbolic constant (defined in the program) */
20             /* a literal constant */
rate     /* a variable */
-1.25    /* another literal constant */
A literal constant evaluates to its own value.  A symbolic constant evaluates to the value it was given when you created it with the #define directive.  A variable evaluates to the value assigned to it by the program.
Complex Expressions
More complex expressions consist of simpler expressions connected by operators.  Here are some examples:
2 + 8
1.25 / 8 + 5 * rate + rate * rate / cost
x = a + 10;
y = x = a + 10;
x = 6 + (y = 4 + 5)
Operators
An operator is a symbol that instructs C to perform some operation, or action, on one or more operands.  An operand is something that an operator acts on.  In C, all operands are expressions.  C operators fall into several categories.
The Assignment Operator
The assignment operator is the equal sign (=).  In a C program, if you write
x = y;
it does not mean “x is equal to y” but rather it means “assign the value of y to x.”  In a C assignment, the right side can be any expression and the left side must be a variable name.  Thus, the form is
variable = expression;
Mathematical Operators
C has two unary mathematical operators and five binary mathematical operators.
The Unary Mathematical Operators
The unary mathematical operators are so named because they take a single operand.
Table 4.1.          C’s unary mathematical operators.
Operator                 Symbol                        Action                                      Example
Increment                + +                   Increments operand by one        + +x,  x+ +
Decrement              - -                     Decrements operand by one      - -x,  x- -
The increment and decrement operators can be used only with variables, not with constants.  The operation performed is to add one to or subtract one from the operand.  In other words, the statements
++x;
- -y;
are the equivalent of
x = x + 1;
y  = y - 1;
Unary operators can be placed before its operand (prefix mode) or after its operand (postfix mode).
*            When used in prefix mode, the increment and decrement operators modify their operand before it is used.
*            When used in postfix mode, the increment and decrement operators modify their operand after it is used.
Listing 4.1         UNARY C.  A program that illustrates the difference between prefix mode and postfix mode.
1:   /* demonstrates unary operator prefix and postfix modes */
2:   #include <stdio.h>
3:   int a, b;
4:   main()
5:   {
6:     /* set a and b both equal to 5 */
7:     a = b = 5;
8:     /* print them, decrementing each time */
9:     /* use prefix mode for b, postfix mode for a */
10:    printf(“\n%d  %d”, a--, --b);
11:    printf(“\n%d  %d”, a--, --b);
12:    printf(“\n%d  %d”, a--, --b);
13:    printf(“\n%d  %d”, a--, --b);
14:    printf(“\n%d  %d”, a--, --b);
15:    return 0;
16:  }
The output for Listing 4.1 is
5      4
4      3
3      2
2      1
1      0
The Binary Mathematical Operators
C’s binary operators take two operands.
Table 4.2.          C’s binary mathematical operators.
Operator                 Symbol                        Action                                                              Example
Addition                 +                      Adds its two operands                                      x + y
Subtraction             -                       Subtracts the second operand from the first                  x - y
Multiplication          *                       Multiplies its two operands                                x * y
Division                  /                       Divides the first operand by the second operand            x / y
Modulus                 %                     Used with integers only.  Gives the remainder when         x % y
                                                      the first operand is divided by the second operand.
The first four operators should be familiar to you, and you should have little trouble using them.  The fifth operator, modulus, may be new.  Modulus returns the remainder when the first operand is divided by the second operand.  For example:
100  %  9  = 1
10  %  5 = 0
11  %  4  = 3
Operator Precedence and Parentheses
Operator Precedence is the order in which operations are performed.  In C, each operator has a specific precedence.  When an expression is evaluated, operators with higher precedence are performed first.  (See Appendix C for complete listing of operator precedence.)
Table 4.3. The precedence of C’s mathematical operators.
Operator                       Relative Precedence
++   - -                          1
*   /   %                         2
+   -                              3
If an expression contains more than one operator with the same precedence level, the operators are performed in left-to-right order as they appear in the expression.  What if the order of precedence does not evaluate your expression as needed?  C uses parentheses to modify the evaluation order.  A subexpression enclosed in parentheses is evaluated first, without regard to operator precedence.
DO / DON’T
DO       use parenthesis to make the order of expression evaluation clear.
DON’T  overload an expression.  It is often more clear to break an expression into two or more statements.  This is especially true when using the unary operators (- -) or ( ++ ).
Relational Operators
C’s relational operators are used to compare expressions.  An expression containing a relational operator evaluates as either true (1) or false (0).
Table 4.4. C’s relational operators.
Operator                          Symbol         Question Asked                                                   Example
Equal                               = =                Is operand 1 equal to operand 2 ?                         x = = y
Greater than                     >                   Is operand 1 greater than operand 2 ?                   x > y
Less than                         <                   Is operand 1 less than operand 2 ?                        x < y
Greater than or equal        >=                 Is operand 1 greater than or equal to operand 2 ?  x >= y
Less than or equal            <=                 Is operand 1 less than or equal to operand 2 ?       x <= y
Not equal                         !=                  Is operand 1 not equal to operand 2 ?                   x != y
DO / DON’T
DO       learn how C interprets true and false.  When working with relational operators, true is equal to 1 and false is equal to 0.
DON’T  confuse = =, the relational operator, with = , the assignment operator.  This is one of the common errors C programmers make!
The if  Statement
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 lines or to not execute at all, depending on the circumstances.  The if statement is one of C’s program control statements.
Syntax:
Form 1 (Simplest)
  if ( expression )
   statement1
  next statement
Example:
if ( x > y)
  printf(“x is greater than y”);
printf(“Hello”);
Form 2 (Common)
if ( expression )
  statement1
else
  statement2
Example:
if ( salary > 450000)
  tax = .30
else
  tax = .25;
Form 3 ( Nested if )
if ( expression )
  statement1
else if ( expression)
  statement2
else
  statement3
next statement
Example:
if ( age < 18)
  printf(“Minor”);
else if ( age < 65)
  printf(“Minor”);
else
  printf(“Senior Citizen”);
DO / DON’T
DO       remember that if you program too much in one day, you’ll get C sick.
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 x equals 2 or not, because each line is evaluated as a separate statement, not together as intended.
            if ( x == 2);             /* semicolon does not belong! */
          statement1;
Evaluation of Relational Expressions
Remember that expressions using relational operators are true C expressions that evaluate, by definition, to a value.  Relational expressions evaluate to a value of either false (0) or true (1).  Although the most common use for relational expressions is within if statements and other conditional constructions, they can be used as purely numeric values.
Precedence of Relational Operators
Table 4.5. C’s relational operators’ precedence order.
Operator                    Relative Precedence
<   <=   >   >=                     1
!=    = =                              2

·         Relational operators have a lower precedence than the mathematical operators.
·         Similarly, you can use parentheses to modify precedence in expressions that use relational operators.

DO / DON’T
DON’T  put assignment statements in if  statements.  This can be confusing to other people who look at your code.  They may think it is a mistake and change your assignment to the logical equal statement.
DON’T  use the “not equal to” operator (!=) in an if statement containing an else.  It is almost always clearer to use the “equal to” operator (= =) with an else.  For example,
                if ( x != 5)
                   statement1;
                else
                   statement2;
                 would be better as
                 if ( x = = 5)
                    statement2;
                 else
                    statement1;
Logical Operators
C’s logical operators enable you to combine two or more relational expressions into a single expression that evaluates as either true or false.
Table 4.6.    C’s logical operators
Operator                          Symbol                                    Example
and                                  &&                                exp1 && exp2
or                                    | |                                  exp1 | |  exp2               
not                                  !                                   ! exp1

Precedence of Relational Operators
Table 4.7. C’s logical operators’ precedence order.
Operator                 Relative Precedence
!                                         1
&&                                     2
| |                                       3
·         The ! operator has a precedence equal to the unary mathematical operators ++ and - -.  Thus, ! has a higher precedence than all the relational operators and all the binary mathematical operators.
·         In contrast, the && and | | operators have much lower precedence, lower than all mathematical and relational operators, although && has a higher precedence than | |.
·         As with all C’s operators, parentheses can be used to modify evaluation order when using the logical operators.
Compound Assignment Operators
C’s compound assignment operators provide a shorthand method for combining a binary mathematical operation with an assignment operation.  The compound assignment operator have the following syntax (where op represents a binary operator):
exp1 op= exp2
which is equivalent to writing
exp1 = exp1 op exp2;
You can create compound assignment operators with the five binary mathematical operators.
Table 4.8. Examples of compound assignment operators.
If you write                         It is equivalent to
x *= y                                 x = x * y
y - = z + 1                           y = y - z + 1
a /= b                                 a = a / b
x += y / 8                            x = x + y / 8
y %= 3                               y = y % 3
The Conditional Operator
The conditional operator is C’s only ternary operator, meaning that it takes three operands.  Its syntax is
exp1 ? exp2 : exp3
If exp1 evaluates as true (that is, nonzero), the entire expression evaluates as the value of exp2.  If exp1 evaluates as false (that is, zero), the entire expression evaluates as the values of exp3.  For example, the statement
x = y ? 1 : 100
assigns the value 1 to x if y is true and assigns 100 to x if  y is false.  Likewise, to make z equal to the larger of x and y, you could write
z = (x > y) ? x : y
The conditional operator can’t be used in all situations in place of an if..else construction, but the conditional operator is more concise.  The conditional operator can also be used in places you can’t use an if statement, such as inside a single printf() statement.
The Comma Operator
The comma is frequently used in C as a simple punctuation mark, serving to separate variable declarations, function arguments, and so on.  In certain situations the comma acts as an operator rather than just as a separator.  You can form an expression by separating two subexpressions with a comma.  The result is as follows:
*                   Both expressions are evaluated, with the left expression being evaluated first.
*                   The entire expression evaluates as the value of the right expression.
For example, the statement
x = (a++ ,  b++);
increments a, then increments b, then assigns the value of b to x.  Because the ++ operator is used in postfix mode, the value of b --- before it is incremented --- is assigned to x.  Using parentheses is necessary because the comma operator has a low precedence, even lower than the assignment operator.
DO / DON’T
DO       use (expression == 0) instead of (! expression).  When compiled, these two expressions evaluate the same; however, the first is more readable.
DO       use the logical operators && and | | instead of nesting if statements.
DON’T  confuse the assignment operator (=) with the equal to (= =) operator.

No comments:

Post a Comment