What is the result of an assignment expression in C? [duplicate]

余生颓废 提交于 2019-11-30 08:47:51

c = 10 is an expression returning 10 which also assigns 10 to c.

Assignment returns with the assigned value. In case c=10 is 10. Since 10!=0, in c it means also true so this is an infinite loop.

It is like you would write

while(10)

Plus You've made the assignment.

If You follow this logic, You can see, that

while(c=0)

would be a loop that never executes its statement or block.

It is said in C99 6.5.16

An assignment operator stores a value in the object designated by the left operand. An        
assignment expression has the value of the left operand after the assignment, but is not an 
lvalue.
Suvarna Pattayil
while((c=10)>0)

c = 10 should return 10.

Now, for while(10>0) 10>0, the > operator returns 1 (non-zero value).

This is an infinite loop. It first assign 10 to c, then compare it with c > 0, then again loop starts, assign 10 to c, compare it with c>0 and so on. Loop never ends. This is equivalent to the following:

while(c=10);

/* Because c assign a garbage value, but not true for all cases maybe it assign 0 */
while(c); 

Edit: It will not return 10 because compiler return only true or false value, so it return true or 1 instead of 10.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!