可以返回函数范围静态变量的引用吗?
我想知道这在任何情况下是否都会产生不良影响。
例如:
Ex1:
void* func1()
{
void* p_ref = NULL;
//function scope static variable
static int var1 = 2;
p_ref = &var1;
return p_ref;
}
Ex2:
//file scope static variable
static int var2 = 2;
void* func2()
{
void* p_ref = NULL;
var2 = 3;
p_ref = &var2;
return p_ref;
}
那么在上述两种情况下,除了 var1 是函数作用域和 var2 是文件作用域这一事实之外,还有什么区别呢?
提前致谢。
I wanted to know if that has any ill effects under any circumsatnce.
For ex:
Ex1:
void* func1()
{
void* p_ref = NULL;
//function scope static variable
static int var1 = 2;
p_ref = &var1;
return p_ref;
}
Ex2:
//file scope static variable
static int var2 = 2;
void* func2()
{
void* p_ref = NULL;
var2 = 3;
p_ref = &var2;
return p_ref;
}
So in the above two cases what is the difference apart from the fact that var1 is function scope and var2 is file scope.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不相信有什么区别。它们都是全局变量,只是第一个变量的名称仅在函数 func1 的范围内可见。
I don't believe there is any difference. They're both global variables, it's just that the name of the first one is only visible inside the scope of the function func1.
除了范围之外,本质上没有区别。
因此,如果该指针,则局部变量是更好的选择
将是访问该变量的唯一方法。
Essentially no difference apart from scope.
Hence, local variable is preferable if that pointer
is going to be the only way to access the variable.