The Comma Operator

I l @ ve RuBoard

The Comma Operator

The comma operator extends the flexibility of the for loop by enabling you to include more than one initialization or update expression in a single for loop specification. For example, Listing 6.11 shows a program that prints first-class postage rates. (At the time of this writing, the rate is 32 cents for the first ounce and 23 cents for each additional ounce. You can check www.usps.gov for the current rates.)

Listing 6.11 The postage.c program.
 /* postage.c - - first-class postage rates */ #include <stdio.h> #define FIRST 32 #define NEXT  23 int main(void) {    int ounces, cost;    printf(" ounces  cost\n");    for(ounces=1, cost=FIRST; ounces<= 16; ounces++,           cost += NEXT)       printf("%5d %7d\n", ounces, cost);   return 0; } 

The first four lines of output look like this:

 ounces  cost    1      32    2      55    3      78 

The program uses the comma operator in the initialize and the update expressions. Its presence in the first expression causes ounces and cost to be initialized . Its second occurrence causes ounces to be increased by 1 and cost to be increased by 23 (the value of NEXT ) for each iteration. All the calculations are done in the for loop specifications (see Figure 6.4)!

Figure 6.4. The comma operator and the for loop.
graphics/06fig04.jpg

The comma operator is not restricted to for loops , but that's where it is most often used. The operator has two further properties. First, it guarantees that the expressions it separates are evaluated in a left-to-right order. (In other words, the comma is a sequence point, so all side effects to the left of the comma take place before the program moves to the right of the comma.) Therefore, ounces is initialized before cost . The order is not important for this example, but it would be important if the expression for cost contained ounces . Suppose, for instance, that you had this expression:

 ounces++, cost = ounces * FIRST 

This would increment ounces , and then use the new value for ounces in the second subexpression. The comma being a sequence point guarantees that the side effects of the left subexpression occur before the right subexpression is evaluated.

Second, the value of the whole comma expression is the value of the right-hand member. The effect of the statement

 x = (y = 3, (z = ++y + 2) + 5); 

is to first assign 3 to y , increment y to 4 , then add 2 to 4 and assign the resulting value of 6 to z , next add 5 to z , and finally assign the resulting value of 11 to x . Why anyone would do this is beyond the scope of this book. On the other hand, suppose you get careless and use comma notation in writing a number:

 houseprice = 249,500; 

This is not a syntax error! Instead, C interprets the right-hand side as a comma expression, with houseprice = 249 being the left subexpression and 500 the right subexpression. Therefore, the value of the whole comma expression is the value of the right-hand expression, and the left substatement assigns the value 249 to the houseprice variable. On the other hand, the statement

 houseprice = (249,500); 

assigns 500, the value of the right subexpression to houseprice .

The comma also is used as a separator, so the commas in

 char ch, date; andprintf("%;d %d\n", chimps, chumps); 

are separators, not comma operators.

Summary: The New Operators

Assignment Operators:

Each of these operators updates the variable at its left by the value at its right, using the indicated operation. The abbreviations R H and L H stand for right-hand for left-hand.

+= Adds the R-H quantity to the L-H variable
-= Subtracts the R-H quantity from the L-H variable
*= Multiplies the L-H variable by the R-H quantity
/= Divides the L-H variable by the R-H quantity
%= Gives the remainder obtained from dividing the L-Hvariable by the R-H quantity

Example:

 rabbits *= 1.6;    is the same as    rabbits = rabbits * 1.6; 

The Comma Operator:

The comma operator links two expressions into one and guarantees that the leftmost expression is evaluated first. It is typically used to include more information in a for loop control expression. The value of the whole expression is the value of the right-hand expression.

Example:

 for (step = 2, fargo = 0; fargo < 1000; step *= 2)         fargo += step; 

Zeno Meets the for Loop

Let's see how the for loop and the comma operator can help solve an old paradox. The Greek philosopher Zeno once argued that an arrow will never reach its target. First, he said, the arrow covers half the distance to the target. Then it has to cover half of the remaining distance. Then it still has half of what's left to cover, ad infinitum. Because the journey has an infinite number of parts , Zeno argued, it would take the arrow an infinite amount of time to reach its journey's end. We doubt, however, that Zeno would have volunteered to be a target just on the strength of this argument.

Let's take a quantitative approach and suppose that it takes the arrow 1 second to travel the first half. Then it would take 1/2 second to travel half of what was left, 1/4 second to travel half of what was left next, and so on. You can represent the total time by the following infinite series:

 1 + 1/2 + 1/4 + 1/8 + 1/16 +.... 

The short program in Listing 6.12 finds the sum of the first few terms.

Listing 6.12 The zeno.c program.
 /* zeno.c -- series sum */ #include <stdio.h> int main(void) {  int count;  double time, x;  int limit;  printf("How many terms do you want?\n");  scanf("%d", &limit);  for (time=0, x=1, count=1; count <= limit; count++, x *= 2.0)  {     time += 1.0/x;     printf("time = %f when count = %d.\n", time, count);  }  return 0; } 

Here is the output for 15 terms:

 How many terms do you want? 15 time = 1.000000 when count = 1. time = 1.500000 when count = 2. time = 1.750000 when count = 3. time = 1.875000 when count = 4. time = 1.937500 when count = 5. time = 1.968750 when count = 6. time = 1.984375 when count = 7. time = 1.992188 when count = 8. time = 1.996094 when count = 9. time = 1.998047 when count = 10. time = 1.999023 when count = 11. time = 1.999512 when count = 12. time = 1.999756 when count = 13. time = 1.999878 when count = 14. time = 1.999939 when count = 15. 

You can see that although you keep adding more terms, the total seems to level out. Indeed, mathematicians have proven that the total approaches 2.0 as the number of terms approaches infinity, just as this program suggests. Here's one demonstration. Suppose you let S represent the sum:

 S = 1 + 1/2 + 1/4 + 1/8 + ... 

Here the ellipses mean "and so on." Then dividing by 2 gives

 S/2 = 1/2 + 1/4 + 1/8 + 1/16 + ... 

Subtracting the second expression from the first gives

 S - S/2 = 1 +1/2 -1/2 + 1/4 -1/4 +... 

Except for the initial value of 1 , each other value occurs in pairs, one positive and one negative, so those terms cancel each, leaving

 S/2 = 1. 

Then, multiplying both sides by 2 gives

 S = 2. 

What about the program itself? It shows that you can use more than one comma operator in an expression. You initialized time , x , and count . After you set up the conditions for the loop, the program itself is extremely brief.

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