[英]How can I tell when a function is accessing a local or external variable?
I am currently attempting to understand this code I came across a C certification test. 我目前正在尝试了解我在C认证测试中遇到的这段代码。 The correct output of the code is 12, 13, 13. I tried printing out the values, before it calls the 3 final outputs and i noticed the reason being is that there's a scope difference between the external x declared at the top and the one inside the function.
代码的正确输出是12、13、13。我尝试打印出这些值,然后再调用3个最终输出,并且我注意到原因是在顶部声明的外部x与外部声明的x之间存在范围差异。在函数内部。 My question is, how do I know which of those functions are accessing which object throughout the code?
我的问题是,我怎么知道在整个代码中哪个函数正在访问哪个对象?
#include <stdio.h>
#include <stdlib.h>
int x;
int modifyvalue()
{
return(x+=10);
}
int changevalue(int x)
{
return(x+=1);
}
int main(){
int x=10;
x++;
printf("[1] %d \n\n", x);
changevalue(x);
printf("[2] %d \n\n", x);
x++;
printf("[3] %d \n\n", x);
modifyvalue();
printf("First output:%d \n\n\n",x);
x++;
changevalue(x);
printf("Second output:%d \n\n\n",x);
modifyvalue();
printf("Third output:%dn \n\n\n",x);
}
Always take the variable from nearest scope. 始终从最近的作用域中获取变量。
Whenever the printf("...", x)
is called, it takes the x
from the function main()
. 每当调用
printf("...", x)
,它将从函数main()
获取x
。
The function modifyvalue()
always operates on the x
outside of all functions. 函数
modifyvalue()
始终在所有函数之外的x
上操作。
The function changevalue(int x)
always operates on the parameter x
- which is a copy of the variable passed in. 函数
changevalue(int x)
始终对参数x
-这是传入变量的副本。
So in your case, both functions essentially do nothing to the x
in main()
. 因此,在您的情况下,这两个函数实际上对
main()
的x
不执行任何操作。
The rule is simple, in every { ... } (block) you can reference either a variable that is define in that block or any "parent" of it. 规则很简单,在每个{...}(块)中,您都可以引用在该块中定义的变量或它的任何“父”变量。 For example in your code:
例如在您的代码中:
Notice that you are printing always "the main's x" that is incremented only in the main. 请注意,您始终在打印“主要部分的x”,仅在主要部分中递增。 As noted by @Jens, the parent scope in C is called enclosing block and the global scope is called program scope (file scope + external)
正如@Jens所指出的,C中的父作用域称为封闭块,全局作用域称为程序作用域(文件作用域+外部作用域)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.