开发者

why does this print? (C language)

Why does the following code run the while loop? I thought "mid = term" is an assignment, not a condition? Please explain. Thanks.

#include <stdio.开发者_StackOverflowh>

main ()
{
    int mid = 4, term = 4;

    while ( mid = term)
    printf("%d\n", --term);
}


The result of an assignment is the value. Therefore the expression evaluates to 4 or a non-zero and thus, in C, TRUE.


mid = term is an expression evaluating to term. So the while loop will run till term = 0.


Because the expression evaluates to true.

Basically, you are saying mid = 4

Since any int that isn't zero, returns true in a conditional statement - the while will loop.


The expression mid = term actually evaluates to the value of mid after assignment. So, what's being evaluated is while(4). Since all nonzero integers are interpreted as true (this is kind of a simplification), the while loop will run as long as term != 0.


Both the assignment and the test happen in the "while" loop, so the printf() executes four times in this case.


Assignment are also expressions which hold a value: the value they assign. mid=0 is an expressions that evals to 0 (thus false).


You assign term to mid and then test the truth of mid. mid is truthy whenever it is non-zero. The loop terminates when term (and hence mid) has been decremented to equal 0, which is falsy.


You are assigning the value of term to mid, then the while checks the value of mid which evaluates to true, until it reaches 0.

This should output:

3
2
1 
0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜