Reputation: 323
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
Reputation: 67780
Comma does not make complex logical operations. You need to use logical operators instead
Upvotes: 0
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