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 ?

有帮助吗?

解决方案

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.

其他提示

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() 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top