Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have while loop test two arguments at the same time without &&/||

Tags:

c

ipc

I was checking Beej's guide to IPC and one line of code took my attention.

In the particular page, the while loop in speak.c has two conditions to check while (gets(s), !feof(stdin)).

So my question is how is this possible as I have seen while look testing only one condition most of the time.

PS: I am little new to these. Will be grateful for any help. Thanks!

like image 999
Shash Avatar asked Sep 08 '26 12:09

Shash


1 Answers

The snippet

while (gets(s), !feof(stdin))

uses the comma operator, first it executes gets(s), then it tests !feof(stdin), which is the result of the condition.

By the way don't use gets, it's extremely unsafe. Be wary of sources using it, they probably aren't good sources for learning the language.

The code

while(gets(s), !feof(stdin)) {
    /* loop body */
}

is equivalent to

gets(s);
while(!feof(stdin)) {
    /* loop body */
    gets(s);
}

just more concise as it avoids the repetition of gets before the loop and in the loop body.

like image 107
Daniel Fischer Avatar answered Sep 11 '26 02:09

Daniel Fischer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!