-2

I have been learning c recently and came across this problem. I understand that b=(a=10)=10 (correct me if my thought process is wrong please) but i can't understand why c=1, so it would be amazing if someone could explain it to me. Thanks

#include <stdio.h>

int main()
{
    int a = 10;
    int b=(a=10);
    int c=(a==10);
    printf("B %d\n",b);
    printf("C %d\n",c);
}
Gui Pinto
  • 9
  • 1
  • 5
    It's a comparison – comparisons *always* yield either 0 or 1, guaranteed by the standard, no matter if ==, !=, <, >, ... – Aconcagua Nov 11 '21 at 15:20
  • 1
    Because `a==10` is a comparison and can be only true or false. Which have values `1` and `0` in C. – Eugene Sh. Nov 11 '21 at 15:21
  • 1
    What did your C book say that `==` returns? That's where should be looking - this isn't an interactive beginner tutorial to replace conventional studies. If you don't understand what the book says, then by all means ask here with an example from the book. – Lundin Nov 11 '21 at 15:24
  • I guess this was a question during exam. The == sign returns either 1 or 0. So at the beginning you set a=10 and then you are asking the computer IF a==10. Logically, the computer answers with 1 which means YES a is equal to 10 – al1en Nov 11 '21 at 16:13

2 Answers2

1

You assign to c the result of expression a == 10 which evaluates to either 1 if condition is true (a is equal to 10) or 0 if condition is false.

a = 10 is an assignment operation while a == 10 is a comparison. Assignments evaluate to the value of the left operand after the assignment is done. In your case you assign a value of 10 to a and then the whole expression evaluates to the value of a afterwards , so 10.

Comparisons evaluate to either 1 or 0 based on whether the two operands are equal or not. In the case of a == 10 they are equal, so the whole expression evaluates to 1.

msaw328
  • 1,459
  • 10
  • 18
  • 1
    FYI, expressions “yield”, “produce”, or “evaluate to” their results. Except for function calls, they do not “return” results, because there is (semantically, regardless of implementation) no call to a subroutine to return from. – Eric Postpischil Nov 11 '21 at 15:32
  • Thanks! Didn't know that true or false would give an actual value to a variable. – Gui Pinto Nov 11 '21 at 15:32
0

a == 10 is a comparison which returns either 1 or 0. As the value of a is 10, this comparison returns 1which is assigned to c. Thus the value of c is 1.

Circuit Breaker
  • 3,298
  • 4
  • 17
  • 19