Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comma separated expression in while loop in C

Tags:

c

I never saw such a while statement before.

while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) {
..
..
}

I read online, that the condition to come out of while loop is the rightmost one [ !feof(stdin) ]. Then, what is the use of the above while statement as opposed to

while(!feof(stdin))
{
       printf("> ");
       fgets(str, 100, stdin);
       ...
       ...
}

Also, while statement takes an expression, so is 1,1,1 a valid expression in C?

like image 234
Aman Jain Avatar asked Dec 06 '10 07:12

Aman Jain


2 Answers

The two loops given don't have the same meaning. By using the comma operator in that way, the author was able to specify code that should be executed every iteration, even if the loop itself is never entered. It's more like a do ... while () loop, or something like the following:

 printf("> ");
 fgets(str, 100, stdin);
 while(!feof(stdin)) {
    ..
    ..

    printf("> ");
    fgets(str, 100, stdin);
 }
like image 162
Justin Spahr-Summers Avatar answered Oct 16 '22 00:10

Justin Spahr-Summers


The comma operator is best thought of as, well, an operator. Just like + is an operator, so that 2 + 3 is an expression (which happens to result in a value of 5), so too , is an operator, and thus 0, 1 is a valid expression (which happens to result in a value of 1, since that was the last operand).

like image 25
Domenic Avatar answered Oct 16 '22 02:10

Domenic