一个C code的输出像通过引用调用 [英] Output of a c code like with call by reference
问题描述
鉴于这种C code:
Given this C code:
int x=12,y=10;
void tswap(int pa, int pb) {
int tmp;
tmp=pa;
pa=pb;
pb=tmp;
x=x+pa;
x=x-pb;
y++;
printf("%d %d %d %d\n",pa,pb,x,y);
}
int main() {
int a=4;
tswap(x,a);
printf("%d %d %d\n",x,y,a);
return 0;
}
我要弄清楚什么如果C使用的call-by-参考它会打印。
I have to figure out what it would print if C used call-by-reference.
下面是我的期望。
首先
的
X = 12 Y = 10和= 4
Here is my expectations.
First of all
x=12 y=10 and a=4
after tswap(12,4):
pa=x=12 pb=a=4
after tmp=pa:
tmp=pa=x=12
-----------
after pa=pb:
tmp=x=12
pa=pb=a=4
-------------
after pb=tmp:
pb=tmp=x=12
pa=a=4
after x=x+pa
x=16
------------
and after x=x-pb and y++
x=4,y=11
所以我认为X = 4,PB = 12,PA = 4,Y = 11;但得到的答复说-4 -4 12 11.如果我错了?
So I think x=4, pb=12, pa=4, y=11; but the answer says -4 12 -4 11. Where I am wrong?
推荐答案
由于没有递归在这里,所有的变量都具有不同的名称,我们可以骗了一下,改变局部变量,全局(因为这不会造成任何名称冲突):
Since there's no recursion here, and all variables have distinct names, we can "cheat" a bit and change the local variables to globals (since this won't cause any name conflicts):
int x=12, y=10; /* original globals */
int tmp; /* belongs to tswap */
int a; /* belongs to main */
void tswap(int pa, int pb) {
tmp=pa;
pa=pb;
pb=tmp;
x=x+pa;
x=x-pb;
y++;
printf("%d %d %d %d\n",pa,pb,x,y);
}
int main() {
a=4;
tswap(x,a);
printf("%d %d %d\n",x,y,a);
return 0;
}
由于 tswap
只调用一次,我们知道它的每年
参数的总是别名为 X
,其 PB
参数的总是的别名为 A
。因此,我们就可以摆脱的参数,使用变量替换他们,他们的别名:
Since tswap
is only called once, we know that its pa
parameter is always aliased to x
, and its pb
parameter is always aliased to a
. So, we can just get rid of the parameters, replacing them with the variables that they alias:
int x=12, y=10;
int tmp;
int a;
void tswap() {
tmp=x;
x=a;
a=tmp;
x=x+x;
x=x-a;
y++;
printf("%d %d %d %d\n",x,a,x,y);
}
int main() {
a=4;
tswap();
printf("%d %d %d\n",x,y,a);
return 0;
}
在这一点上,这只是常规的C code;我们不再有任何参数,因此传递通过引用和传递按值是等价的。通过追踪:
At this point, this is just regular C code; we no longer have any parameters, so "pass-by-reference" and "pass-by-value" are equivalent. Tracing through:
int x=12, y=10;
int tmp;
int a;
void tswap() {
tmp=x; /* x=12, y=10, tmp=12, a=4 */
x=a; /* x=4, y=10, tmp=12, a=4 */
a=tmp; /* x=4, y=10, tmp=12, a=12 */
x=x+x; /* x=8, y=10, tmp=12, a=12 */
x=x-a; /* x=-4, y=10, tmp=12, a=12 */
y++; /* x=-4, y=11, tmp=12, a=12 */
printf("%d %d %d %d\n",x,a,x,y); /* prints "-4 12 -4 11" */
}
int main() {
a=4; /* x=12, y=10, tmp is uninitialized, a=4 */
tswap(); /* x=-4, y=11, tmp=12, a=4; prints "-4 12 -4 11" */
printf("%d %d %d\n",x,y,a); /* prints "-4 11 4" */
return 0;
}
这篇关于一个C code的输出像通过引用调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!