我正在经历C的udemy课程,发现这个问题不是两个都声明相同吗?如果是,为什么答案不同
源代码:
#include <stdio.h>
void swap(int *a, int *b){
int temp;
temp =*a; // This works
//*a = temp; // This does not work?
*a = *b;
*b=temp;
}
int main()
{
int x=100, y=400;
printf("before swapping x is %d and y is %d\n",x,y);
swap(&x,&y);
printf("after swapping x is %d and y is %d",x,y);
return 0;
}
为什么从temp=*a
到*a=temp
的结果不同?
答案 0 :(得分:1)
不,这不是一回事。运算符=
修改左操作数,使其获得与右操作数相同的值。称为分配。
此代码段可以说明这一点:
int x=3, y=5;
printf("Before assignment: x: %d y: %d\n", x, y);
x=y;
printf("After assignment: x: %d y: %d\n", x, y);
它将打印以下内容:
Before assignment: x: 3 y: 5
After assignment: x: 5 y: 5
如果将x=y
切换为y=x
,则会得到:
Before assignment: x: 3 y: 5
After assignment: x: 3 y: 3