Question

Couldn't find a better title, so edit it if you have a better idea.

Here is while loop in C:

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

How does the condition work?

How does (c = getchar()) assignment expression "return" a value, as it is then compared to EOF ?

Was it helpful?

Solution

In C an assignement operation is en expression whose value is the result of the assignment.

For example a = 5 is an expression whose value is 5.

((c = getchar()) != EOF calls getchar and puts the return value in c and then compares the result (now the content of c) = to EOF.

OTHER TIPS

The expression of the assignment returns the assigned value.

When you do:

((c = getchar()) != EOF)

You're comparing the assigned value to EOF.

In C, the assignment expression has itself the value of the assigned value.

This property allows the programmer to apply different techniques like the one you mentioned, directly comparing the assigned value.

if ((a = f()) != 0) ....

or multiple assignments

a = b = f() 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top