这个问题在这里已有答案:
我是新手。所以请耐心等待,
#include<stdio.h>
int abc(int k)
{
k++;
}
int main()
{
int a=1;
printf("%d",abc(a));
return 0;
}
以上程序的输出是:1
我的问题是输出不应该是'2',因为实际参数将'1'的值传递给形参,并且必须通过函数abc递增。
当我将函数调用更改为
printf("%d",abc(1));
输出是一些垃圾值。
参数传递如何在这里工作?请解释。
您获得的意外结果不是由“参数传递”产生的,而是来自abc
函数不返回任何值的事实。您应该使用return k;
语句来获得您期望的输出。但是对于参数传递,它们是通过值传递的,即传递的值被复制到临时位置k
(仅在函数中可见),而不是在它之外修改。
您已经通过值传递a
的代码示例。你可以把它想象成a
的副本。您使用注释修改了代码:
#include<stdio.h>
int abc(int k)
{
// k is a copy of a, it is not a, since k is a copy, it has the
// value of a at the point of the copy. So, k is 1
k++; // k is now 2
return k; // return the computed value to the caller and destroy k
}
int main()
{
int a=1;
// as previously written, without the return statement in abc()
// this function returned nothing. So, the compiler just arranges
// for something to be used from the stack where the return would
// have placed 2. (I'm not terribly familiar
// with assembly and so I'm not sure which register it would use).
// That's why you get non-nonsensical data, whatever is in memory is
// what you get and without the return statement, there's nothing
// meaningful there.
// Also, as I commented above, abc() takes a **copy** of a. Thus,
// the contents of a are unmodified. See how the printf() is
// changed. What does it print?
printf("%d %d",abc(a), a);
return 0;
}