简体   繁体   English

有人可以向我解释为什么 c=1 吗?

[英]Can someone explain to me why c=1?

I have been learning c recently and came across this problem.我最近一直在学习 c 并遇到了这个问题。 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.我明白 b=(a=10)=10 (如果我的思维过程有误,请纠正我)但我不明白为什么 c=1,所以如果有人能向我解释它会很神奇。 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的结果分配给 c,如果条件为真(a 等于 10)则返回 1,如果条件为假则返回 0。

a = 10 is an assignment operation while a == 10 is a comparison. a = 10是赋值操作,而a == 10是比较。 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.在您的情况下,您将值 10 分配给 a,然后返回 a 的值,因此a = 10计算结果为 10。

Comparisons return either 1 or 0 based on whether the two operands are equal or not.根据两个操作数是否相等,比较返回 1 或 0。 In the case of a == 10 they are equal, so the whole expression evaluates to 1.a == 10的情况下,它们相等,因此整个表达式的计算结果为 1。

a == 10 is a comparison which returns either 1 or 0 . a == 10是一个比较,它返回10 As the value of a is 10, this comparison returns 1 which is assigned to c .由于a值为 10,因此此比较返回1分配给c Thus the value of c is 1 .因此c值为1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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