Once in a while, you find yourself in a situation in which C expects a single expression, but you have two things you want to say. The most common (and in fact the only common) example is in a for loop, specifically the first and third controlling expressions. What if (for example) you want to have a loop in which i counts up from 0 to 10 at the same time that j is counting down from 10 to 0? You could manipulate i in the loop header and j ``by hand'':
j = 10; for(i = 0; i < 10; i++) { ... rest of loop ... j--; }but here it's harder to see the parallel nature of i and j, and it also turns out that this won't work right if the loop contains a continue statement. (A continue would jump back to the top of the loop, and i would be incremented but j would not be decremented.) You could compute j in terms of i:
for(i = 0; i < 10; i++) { j = 10 - i; ... rest of loop ... }but this also makes j needlessly subservient. The usual way to write this loop in C would be
for(i = 0, j = 10; i < 10; i++, j--) { ... rest of loop ... }Here, the first (initialization) expression is
i = 0, j = 10The comma is the comma operator, which simply evaluates the first subexpression i = 0, then the second j = 10. The third controlling expression,
i++, j--also contains a comma operator, and again, performs first i++ and then j--.
Precisely stated, the meaning of the comma operator in the general expression
e1 , e2is ``evaluate the subexpression e1, then evaluate e2; the value of the expression is the value of e2.'' Therefore, e1 had better involve an assignment or an increment ++ or decrement -- or function call or some other kind of side effect, because otherwise it would calculate a value which would be discarded.
There's hardly any reason to use a comma operator anywhere other than in the first and third controlling expressions of a for loop, and in fact most of the commas you see in C programs are not comma operators. In particular, the commas between the arguments in a function call are not comma operators; they are just punctuation which separate several argument expressions. It's pretty easy to see that they cannot be comma operators, otherwise in a call like
printf("Hello, %s!\n", "world");the action would be ``evaluate the string "Hello, %s!\n", discard it, and pass only the string "world" to printf.'' This is of course not what we want; we expect both strings to be passed to printf as two separate arguments (which is, of course, what happens).
Read sequentially: prev next up top
This page by Steve Summit // Copyright 1996-1999 // mail feedback