-1

Suppose this while loop:

while ((c = getchar()) != EOF)
        ^^^^^^^^^^^^^      
         assignment

As you can see we're going to compare an assignment to EOF, how it could be happened? As far as I know, assignment doesn't return any value so you can't compare an assignment (right?)

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201
  • 1
    assignment usually returns value: you can use that for "a = b = c = 0; " or in the condition like in your example... – V-X May 07 '13 at 10:04
  • 1
    It is an expression rather than a mere assignment in the C language. – BLUEPIXY May 07 '13 at 10:05
  • You need to get used to the concepts of **value** and **side-effect** of (sub)expressions. The **value** of `c = getchar()` is, basically, whatever the user typed; the **side-effect** is changing the value of `c`. – pmg May 07 '13 at 10:08
  • (right?) wrong! it does return a value – Lefteris E May 07 '13 at 11:19

2 Answers2

3

The expression of the assignment returns the assigned value, in the case of while ((c = getchar()) != EOF) you are comparing the next character from the standard input (what getchar() returns - which is the assigned value) with EOF.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

whenever we call getchar(), it reads the next character of input and returns it to you. The function returns an int, being the ASCII code of the relevant character, but you can assign the result to a char variable if you want. So by this manner variable c is getting value which is finaly compared with EOF.This loop will run until file will reach at it's end.

Dayal rai
  • 6,548
  • 22
  • 29