While loop format in C [duplicate]
Possible Duplicate:
comma separated expression in while loop in C
Hi All, Has anybody ever encountered this format of while loop in C?
If yes, what is the syntax? I am not able to understand this. Please help.
Regards kingsmasher1
while(printf("> "), fgets(str, 100, stdin), !feof(stdin))
{
}
This is an excellent example of evil code. Do not write code like this. It is hard to read and debug. It is useful only in obfuscated C contests or to otherwise demonstrate how clever you are. In some jurisdictions, it may render you liable to charges of compiler abuse. Using code like this may cause subsequent maintainers to hunt you down and LART you with extreme prejudice. In extreme cases, Randall Munroe may make fun of you.
Your loop is equivalent to:
do {
printf("> ");
fgets(str, 100, stdin);
} while(!feof(stdin));
This is an instance of the Comma Operator: http://en.wikipedia.org/wiki/Comma_operator Two instances, actually.
The comma operator evaluates the expression on the left hand side of the comma first, then the one on the right, returning the latter as the value of the entire expression.
So in this case, it's equivalent to
do
{
printf("> ");
fgets(str, 100, stdin);
} while (!feof(stdin));
I don't recommend writing obtuse code like this. The comma operator is rarely used - typically in macros which should act like an expression but actually execute a sequence of operations.
That's an abuse of the comma operator.
What it does is
while(printf("> "), fgets(str, 100, stdin), !feof(stdin))
it evaluates each of the expressions separated by the comma operator and discards the values of all but the rightmost one. It uses the value of the right most one as the value of the whole expression. So, you have
while (expression) /*...*/;
and, your expression
is
printf("> "), fgets(str, 100, stdin), !feof(stdin)
That expression:
- prints a greater than sign and a space evaluating to 2; it discards the 2
- reads at most 100 chars from
stdin
intostr
and evalutes to eitherstr
or NULL if there was an error. That value (str
or NULL) is discarded - it sees if the stream
stdin
is in an end-of-file condition and the value is the value of the whole expression (1 ifstdin
is in end-of-file condition; 0 otherwise)
精彩评论