-
Comma Operator
The sample code below uses comma operator,
Code:
#include <stdio.h>
int inc(int i)
{
return ++i;
}
int main(int argc, char **argv)
{
int a,b,c;
a = b = c = 0;
while( ++a, a=inc(a), a < 3)
{
while( b=1, c=inc(c), c < 3)
++b, b=inc(b), ++b;
}
printf("%d %d %d\n", a,b,c);
}
I don't understand the condition(s) in the while-loop,
all the 3 conditions are to be satisfied (or) it is totally one condition
- If it is one condition then what is the return value of the condition? i.e., which statement's return value is it?.
- If it is 3 conditions then is ',' similar to '&&' ??
( ++a, a=inc(a), a<3 )
Please somebody tell me in short, How to use ',' operator?
-
The comma operator seperates two expressions which are
evaluated left to right. The result of the right expression is
returned as the value of the whole thing. So, taking the
example from K&R:
Code:
f(a, (t=3, t+2), c);
The second argument passed to the function uses a comma
operator (the parentheses are needed) and the value is 5.
in your example:
Code:
while( b=1, c=inc(c), c < 3)
++b, b=inc(b), ++b;
/* is equivalent to */
b=1;
c=inc(c);
while(c < 3) {
++b;
b=inc(b);
++b;
b=1; /* makes the rest of the loop rather pointless! */
c=inc(c);
}
HTH
-
great explanation!!!!
Thanx a lot.