简体   繁体   中英

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;
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM