简体   繁体   English

C函数返回值的范围

[英]Scope of return value of a function in C

int Mul (int x)
{
   int y =0;
   y = x *3;
   return y;
}

int Main(void)
{   
   int var =0;
   scanf ("%d", &var);
   int result =0;
   result = Mul(var);
   printf ("%d", result);
}

Now my question is: 现在我的问题是:
The variable y is created on the stack and when the function Mul returns, it gets cleared. 变量y是在堆栈上创建的,当函数Mul返回时,它将被清除。 Then how it is assigned to result? 那么如何分配结果呢?

result = Mul(var);

C considers the function "Mul" to have this value upon return, as though it were a variable. C认为函数“ Mul”在返回时就具有此值,就好像它是一个变量一样。 Note that Mul is declared as an int. 请注意,Mul被声明为int。 Using "return" puts the value of y on the stack to be used in the assignment to "result". 使用“返回”会将y的值放在要分配给“结果”的堆栈中。 This value is popped from the stack which in effect clears it. 从堆栈中弹出该值,实际上将其清除。

The statement return y; 语句返回y; Does not return the value of y but a copy of the value of y. 不返回y的值,而是y值的副本。 This copy is stored in the result variable. 该副本存储在结果变量中。 When you execute the code again with new values for x and y, the old values are overwritten. 当使用x和y的新值再次执行代码时,旧值将被覆盖。

  1. You are returning the value of the variable (y) not the variable it self. 您将返回变量(y)的值,而不是其自身的变量。 Also variable "y" is local to mul function , so you cant return "y" as its scope is local to that function. 另外,变量“ y”是mul函数的局部变量,因此您不能返回“ y”,因为它的作用域是该函数的局部变量。

  2. Whenever there is function call other than the void data type, the function call statement is replaced by the value that function is returning. 只要有除void数据类型以外的函数调用,函数调用语句就会被函数返回的值替换。

For eg. 例如。

In your case if x=3 then y= 3*3 evaluates to 9 thus 在您的情况下,如果x = 3,则y = 3 * 3计算为9,因此

y=9

and

return y 

simply means return 9 just like you return 0. 仅仅意味着返回9就像返回0一样。

so the expression 所以表达

result=mul(var) //is replaced by result=9.

I think this is enough of explanation 我认为这足以解释

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

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