Consider following code:
int main()
{
char c;
for(;(c=getchar())+1;)
printf("%c\n",c);
}
It gets characters what I enter in terminal and prints them. When I remove +1
in condition, program works but it doesnt stop when EOF
(Ctrl+D) signal. When I change it to +2
same problem.
My question is how that +1
work? Is it something related to getchar()
or for
loop?
That is because the int value of EOF
is -1
, so what you're doing is loop until the expression(c=getchar())+1
) gets the value 0 which is when you read EOF
(where value of exrpession is: -1+1=0). Also as wll pointed out in the comments you should declare c as int since getchar() returns int.