Domanda

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 ?

È stato utile?

Soluzione

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.

Altri suggerimenti

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() 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top