简体   繁体   中英

Can someone explain to me why c=1?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM