S.Sot
S.Sot

Reputation: 323

using comma operator in the body of a loop

I'm trying to write a while loop in two different ways and noticed that using ',' in the condition twice doesn't work the way I think it does. I'm just curious about what actually happens. Here's the code :

#include <stdio.h>

int main()
{
    int i = 0, lim = 1000, c;
    char s[lim];
    while (i < lim - 1, (c = getchar()) != '\n')
    {
        if (c != EOF)
        {
            s[i] = c;
        }
        else
        {   
            break;
        }
        ++i;
    }
    printf("%s\n", s);
    return 0;
}
#include <stdio.h>

int main()
{
    int i = 0, lim = 1000, c;
    char s[lim];
    while (i < lim - 1, (c = getchar()) != '\n', c != EOF)
    {
        s[i] = c;
        ++i;
    }
    printf("%s\n", s);
    return 0;
}

Upvotes: 0

Views: 60

Answers (2)

0___________
0___________

Reputation: 67780

Comma does not make complex logical operations. You need to use logical operators instead

Upvotes: 0

klutt
klutt

Reputation: 31409

Lets look at the while condition:

i < lim - 1, (c = getchar()) != '\n', c != EOF

The first part, i < lim -1 has no effect whatsoever. The second part will execute c = getchar(), but the comparison with '\n' is completely discarded. The return value of the whole condition is that of c != EOF. So the condition is equivalent to:

(c = getchar()) != EOF

What you can do is to change the comma operator for && instead.

i < lim - 1 && (c = getchar()) != '\n' && c != EOF

Upvotes: 5

Related Questions