18

In the following code:

int c;
while((c=10)>0)

What does c = 10 evaluate to? Is it 1 which indicates that the value 10 is assigned to variable c successfully, or is it 10? Why?

Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175
user2131316
  • 3,111
  • 12
  • 39
  • 53

5 Answers5

17

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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • if it assigns 10 to c, but should c = 10 return 1? – user2131316 May 15 '13 at 14:24
  • 1
    That would not be nice, think about the statement a = c = 10; Wouldn't you want a to be 10, not 1? – Bathsheba May 15 '13 at 14:25
  • 5
    @user2131316: the *expression* `c = 10` has the value of `c` after the assignment ([N1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), 6.5.15/3). Assignment expressions are not Boolean expressions. – John Bode May 15 '13 at 15:03
  • It doesn't return 10, it returns `c` which is 10 for the first call. The difference is that the value of `c` will most likely change in the `while` block. – ramazan polat Aug 31 '20 at 08:34
13

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.
Gurity
  • 445
  • 5
  • 10
  • Best answer - clear, precise and short – martinkunev Dec 25 '19 at 10:45
  • 1
    To follow up @martinkunev's answer: this answer is also better because it references the standard directly, and more directly speaks to the question of the type of the expression's value, which matches the type of the left-hand operand. (Consider *a=b=c* where *a* and *c* are *unsigned int* and *b* is *unsigned short*.) – Max Barraclough May 02 '20 at 10:51
  • 1
    This also means that `int x = 10; int y = (x += 1);` results in `x = 11, y = 11`, **not** `x = 11, y = 1`. – Qix - MONICA WAS MISTREATED Nov 19 '20 at 03:23
2

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.

1

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.

Ashish Rawat
  • 3,363
  • 5
  • 29
  • 35
1
while((c=10)>0)

c = 10 should return 10.

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

Community
  • 1
  • 1
Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59