函数返回本地变量,尽管变量不超出范围,没有编译器问题,并且代码执行

function returns local variable, though variable is out of scope no compiler issues and code executes

本文关键字:变量 编译器 问题 范围 代码 执行 返回 函数      更新时间:2023-10-16

我的功能应该返回本地变量。即使变量不超出范围,它也可以在没有任何编译器问题的情况下执行此操作。

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由值返回。因此,呼叫者在result中获取值的副本,然后随后使用此副本。 result本身不符合范围,并且无法再次访问。

如果您的变量是指指针,那是不正确的。您可以从这个问题中阅读有关它的更多信息。

此外,您似乎完全忘记了使用add()。我想你打算使用

res = add(3,4);

main()中而不是

res = (3 + 4);