我是新手。所以请耐心等待,
#include<stdio.h>
int abc(int k)
{
k++;
}
int main()
{
int a=1;
printf("%d",abc(a));
return 0;
}
以上程序的输出为:1
我的问题是输出不应该是&#39; 2&#39;因为实际参数传递的是&#39; 1&#39;到形式参数,它必须通过函数abc递增。
当我将函数调用更改为
时printf("%d",abc(1));
输出是一些垃圾值。
参数传递如何在这里工作?请解释一下。
答案 0 :(得分:5)
您获得的意外结果不是由&#34;参数传递&#34;而是由于abc
函数未返回任何值。您应该使用return k;
语句来获得您期望的输出。但是对于参数传递,它们是按值传递的,即传递的值被复制到临时位置k
(仅在函数中可见),而不是在其外部修改。
答案 1 :(得分:0)
您已通过值{/ 1>传递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;
}