gpt4 book ai didi

c++ - 函数返回局部变量,尽管变量超出范围,没有编译器问题并且代码执行

转载 作者:行者123 更新时间:2023-11-30 21:43:29 25 4
gpt4 key购买 nike

我的函数应该返回一个局部变量。即使变量超出范围,它也能在没有任何编译器问题的情况下做到这一点。

int add(int a, int b);
{
int result=0;
result = a + b;
return (result); // result scope should be limited to this method
}

int main()
{
int res=0;
res = (3 + 4);
printf("Result : %d \n", res);
return 0;
}

任何人都可以解释一下这种行为吗?

最佳答案

当你这样做时

return (result);

结果按值返回。因此,调用者获取 result 中值的拷贝,并随后使用该拷贝。 结果本身超出范围,并且不会再次访问。

如果你的变量是一个指针,那就是不正确的。您可以阅读更多相关信息from this question .

此外,您似乎根本忘记使用add()。我想你打算使用

res = add(3,4);

main() 中而不是

res = (3 + 4);

关于c++ - 函数返回局部变量,尽管变量超出范围,没有编译器问题并且代码执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43567594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com