Expressions and Statements

I l @ ve RuBoard

Expressions and Statements

We have been using the terms expression and statement throughout these first few chapters, and now the time has come to study their meanings more closely. Statements form the basic program steps of C, and most statements are constructed from expressions. This suggests that you look at expressions first.

Expressions

An expression consists of a combination of operators and operands. (An operand , recall, is what an operator operates on.) The simplest expression is a lone operand, and you can build in complexity from there. Here are some expressions:

 4 -6 4+21 a*(b + c/d)/20 q = 5*2 x = ++q % 3 q > 3 

As you can see, the operands can be constants, variables , or combinations of the two. Some expressions are combinations of smaller expressions, called subexpressions . For instance, c/d is a subexpression of the fourth example.

Every Expression Has a Value

An important property of C is that every C expression has a value. To find the value, you perform the operations in the order dictated by operator precedence. The value of the first few expressions we just listed is clear, but what about the ones with = signs? Those expressions simply have the same value that the variable to the left of the = sign receives. Therefore, the expression q=5*2 as a whole has the value 10 . What about the expression q > 3 ? Such relational expressions have the value 1 if true and if false. Here are some expressions and their values:

Expression Value
-4 + 6 2
c = 3 + 8 11
5 > 3 1
6 + (c = 3 + 8) 17

The last expression looks strange ! However, it is perfectly legal in C because it is the sum of two subexpressions, each of which has a value.

Statements

Statements are the primary building blocks of a program. A program is a series of statements with some necessary punctuation thrown in. A statement is a complete instruction to the computer. In C, statements are indicated by a semicolon at the end. Therefore,

 legs = 4 

is just an expression (which could be part of a larger expression), but

 legs = 4; 

is a statement.

What makes a complete instruction? First, C considers any expression to be a statement if you append a semicolon. (These are called expression statements .) Therefore, C won't object to lines such as the following:

 8; 3 + 4; 

However, these statements do nothing for your program and can't really be considered sensible statements. More typically, statements change values and call functions:

 x = 25; ++x; printf("x = %d\n", x); 

Although a statement (or, at least, a sensible statement) is a complete instruction, not all complete instructions are statements. Consider the following statement:

 x = 6 + (y = 5); 

In it, the subexpression y = 5 is a complete instruction, but it is only part of the statement. Because a complete instruction is not necessarily a statement, a semicolon is needed to identify instructions that truly are statements.

So far you have encountered four kinds of statements. Listing 5.13 gives a short sample that uses all four.

Listing 5.13 The addemup.c program.
 /* addemup.c -- four kinds of statements */ #include <stdio.h> int main(void)                /* finds sum of first 20 integers */ {   int count, sum;             /* declaration statement          */      count = 0;                  /* assignment statement           */   sum = 0;                    /* ditto                          */   while (count++ < 20)     /* while                          */      sum = sum + count;       /*     statement                  */   printf("sum = %d\n", sum);  /* function statement             */   return 0; } 

Let's discuss Listing 5.13. By now, you must be pretty familiar with the declaration statement . Nonetheless, we will remind you that it establishes the names and type of variables and causes memory locations to be set aside for them. Note that a declaration statement is not an expression statement. That is, if you remove the semicolon from a declaration, you get something that is not an expression and that does not have a value:

 int port                       /* not an expression, has no value */ 

The assignment statement is the workhorse of most programs; it assigns a value to a variable. It consists of a variable name followed by the assignment operator ( = ) followed by an expression followed by a semicolon. Note that the while statement includes an assignment statement within it. An assignment statement is an example of an expression statement.

A function statement causes the function to do whatever it does. In this example, the printf() function is invoked to print some results. A while statement has three distinct parts (see Figure 5.6). First is the keyword while . Then, in parentheses, is a test condition. Last is the statement that is performed if the test is met. Only one statement is included in the loop. It can be a simple statement, as in this example, in which case no braces are needed to mark it off, or the statement can be a compound statement, like some of the earlier examples, in which case braces are required. Read about compound statements just ahead.

Figure 5.6. Structure of a simple while loop.
graphics/05fig06.jpg

The while statement belongs to a class of statements sometimes called structured statements because they possess a structure more complex than that of a simple assignment statement. In later chapters, you will encounter many other kinds of structured statements.

Side Effects and Sequence Points

Now for a little more C terminology. A side effect is the modification of a data object or file. For instance, the side effect of the statement

 states = 50; 

is to set the states variable to 50 . Side effect? This looks more like the main intent! From the standpoint of C, however, the main intent is evaluating expressions. Show C the expression 4 + 6 , and C evaluates it to 10. Show it the expression states = 50 , and C evaluates it to 50. Evaluating that expression has the side effect of changing the states variable to 50 . The increment and decrement operators, like the assignment operator, have side effects and are used primarily because of their side effects.

A sequence point is a point in program execution at which all side effects are evaluated before going on to the next step. In C, the semicolon in a statement marks a sequence point. That means all changes made by assignment operators, increment operators, and decrement operators in a statement must take place before a program proceeds to the next statement. Some operators that we'll discuss in later chapters have sequence points. Also, the end of any full expression is a sequence point.

What's a full expression? It's one that's not a subexpression of a larger expression. Examples of full expressions include the expression in an expression statement and the expression serving as a test condition for a while loop.

Sequence points help clarify when postfix incrementation takes place. Consider, for instance, the following code:

 while (guests++ < 10)      printf("%d \n", guests); 

Sometimes C newcomers assume that "use the value, then increment it" means, in this context, to increment guests after it's used in the printf() statement. However, the guests++ < 10 expression is a full expression because it is a while loop test condition, so the end of this expression is a sequence point. Therefore, C guarantees that the side effect (incrementing guests ) takes place before the program moves on to printf() . Using the postfix form, however, guarantees that guests will be incremented after the comparison to 10 is made.

Now consider this statement:

 y = (4 + x++) + (6 + x++); 

The expression 4 + x++ is not a full expression, so C does not guarantee that x will be incremented immediately after the subexpression 4 + x++ is evaluated. Here, the full expression is the entire assignment statement, and the semicolon marks the sequence point, so all that C guarantees is that x will have been incremented twice by the time the program moves to the following statement. C does not specify whether x is incremented after each subexpression is evaluated or only after all the expressions have been evaluated, which is why you should avoid statements of this kind.

Compound Statements (Blocks)

A compound statement is two or more statements grouped together by enclosing them in braces; it is also called a block . The shoe2.c program used a block to let the while statement encompass several statements. Compare the following program fragments :

 /* fragment 1 */ index = 0; while (index++ < 10)   sam = 10 * index + 2; printf("sam = %d\n", sam); /* fragment 2 */ index = 0; while (index++ < 10) {   sam = 10 * index + 2;   printf("sam = %d\n", sam); } 

In fragment 1, only the assignment statement is included in the while loop. In the absence of braces, a while statement runs from the while to the next semicolon. The printf() function will be called just once, after the loop has been completed.

In fragment 2, the braces ensure that both statements are part of the while loop, and printf() is called each time the loop is executed. The entire compound statement is considered to be the single statement in terms of the structure of a while statement (see Figure 5.7).

Figure 5.7. A while loop with a compound statement.
graphics/05fig07.jpg

Style Tips

Look again at the two while fragments and notice how an indentation marks off the body of each loop. The indentation makes no difference to the compiler; it uses the braces and its knowledge of the structure of while loops to decide how to interpret your instructions. The indentation is there for you, so that you can see at a glance how the program is organized.

I have shown one popular style for positioning the braces for a block, or compound, statement. Another very common style is this:

 while (index++ < 10) {   sam = 10*index + 2;   printf("sam = %d \n", sam); } 

This style highlights the attachment of the block to the while loop. The other style emphasizes that the statements form a block. Again, as far as the compiler is concerned , both forms are identical.

To sum up, use indentation as a tool to point out the structure of a program to the reader.

Summary: Expressions and Statements

Expressions:

An expression is a combination of operators and operands. The simplest expression is just a constant or a variable with no operator, such as 22 or beebop . More complex examples are 55 + 22 and vap = 2 * (vip + (vup = 4)) .

Statements:

A statement is a command to the computer. There are simple statements and compound statements. Simple statements terminate in a semicolon, as in these examples:

Declaration statement: int toes;
Assignment statement: toes = 12;
Function call statement: printf("%d\n", toes);
Structured statement: while (toes < 20) toes = toes + 2;
NULL statement: ; /* does nothing */

Compound statements , or blocks , consist of one or more statements (which themselves can be compound) enclosed in braces. The following while statement contains an example:

 while (years < 100) {     wisdom = wisdom + 1;     printf("%d %d\n", years, wisdom);     years = years + 1; } 
I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net