Home > Software design >  Can someone explain to me why c=1?
Can someone explain to me why c=1?

Time:11-12

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);
}

CodePudding user response:

You assign to c the result of expression a == 10 which returns 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 return 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 value of a afterwards is returned, so a = 10 evaluates to 10.

Comparisons return 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.

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related