0

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;
}
klutt
  • 30,332
  • 17
  • 55
  • 95
S.Sot
  • 321
  • 1
  • 7
  • What did you think it does? Afaik the comma operator simply returns one of the two values. See https://stackoverflow.com/a/52558/2550406 – lucidbrot Nov 17 '19 at 20:31
  • Don’t use comma in loops. It means it will ignore all but last condition. Use and/or – Sami Kuhmonen Nov 17 '19 at 20:33
  • All the comma'd expressions will be evaluated, and the value of the final one controls the loop. Consider using the logical `&&` but beware of short-circuit and side-effects. – Weather Vane Nov 17 '19 at 20:35
  • Yes, thank you. I wasn't aware of what the coma does. The point of the exercise was to not use && or ||. – S.Sot Nov 17 '19 at 20:39
  • `printf("%s\n", s);` is UB. `s` is not a _string_ as it lacks a _null character_. Add `s[i] = 0;` after the loop. – chux - Reinstate Monica Nov 17 '19 at 20:44

2 Answers2

5

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
klutt
  • 30,332
  • 17
  • 55
  • 95
0

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

0___________
  • 60,014
  • 4
  • 34
  • 74