函数返回本地变量,尽管变量不超出范围,没有编译器问题,并且代码执行
function returns local variable, though variable is out of scope no compiler issues and code executes
我的功能应该返回本地变量。即使变量不超出范围,它也可以在没有任何编译器问题的情况下执行此操作。
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);
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- C++编译器是否优化了顺序静态变量读取?
- 有没有办法强制C++编译器将变量存储在寄存器中?
- 如果函数包含静态变量,为什么编译器不执行内联?
- 现代c++编译器会优化不可变的临时变量吗
- 是否允许编译器优化掉局部易失性变量
- 现代编译器会优化只引用对象子集的局部变量吗
- (C++)for循环中的空初始语句是否保存所有编译器中变量的上一次初始化
- 如何在编译器时动态获取元组内的变量类型C++?
- 奇怪的未声明变量编译器错误
- 是否可以将移动的变量标记为不再可用,并在使用它时收到编译器警告?
- 编译器是否足够聪明,以至于 std::move 变量超出范围?
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 使用常量变量作为维度将矩阵声明为类成员时出现编译器错误
- Eclipse 编译器有没有办法将变量中的地址字段显示为整数值?
- 为什么编译器并不总是优化局部变量?
- 关于基类中的显式模板实例化和静态变量:编译器错误或规范的有效解释
- 无法引用专用静态成员变量:编译器错误