1

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?

  • 5
    Because `EOF` is typically defined as `-1`, and `-1 + 1 = 0`. In short, don't do that. What you should do is `while((c=getchar()) != EOF)` – user3386109 Oct 15 '16 at 17:22
  • 4
    And, `char c;` --> `int c;` because `getchar()` returns `int`. – Weather Vane Oct 15 '16 at 17:23
  • 1
    To emphasise on what @user3386109 and @WeatherVane wrote: you have to use both measures! EOF **typically** is `-1`, it is not guaranteed! General advice: Read the documentation of functions and macros, etc. you use! It all can be found in any C book. Along with what an addition means in C (the mathematical basics should be tought at school).. – too honest for this site Oct 15 '16 at 17:37
  • http://stackoverflow.com/a/35356684/2681632 a lengthy but good answer of the dangers of `char c = getchar()`. – Ilja Everilä Oct 15 '16 at 17:38

3 Answers3

1

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.

coder
  • 12,832
  • 5
  • 39
  • 53
1

for statement works with limits known already if you want a conditional loop use while :

int main()
{
int c;
while ((c=getchar()) != eof())
    printf("%c\n",c);
}
melbx
  • 319
  • 1
  • 3
  • 17
1

Reason why it works for +1 only.

Prototype : int getchar(void);

Return Value

  • On success, the character read is returned (promoted to an int value).

  • The return type is int to accommodate for the special value EOF, which indicates failure(-1).

  • If the standard input was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stdin.

  • If some other reading error happens, the function also returns EOF, but sets its error indicator (ferror) instead.

prophet1906
  • 123
  • 7