search

Home  >  Q&A  >  body text

变量 - c++为什么只能输出一次

int& geta()
{

int a=20;
return a;
}
int main()
{
int& a1=geta();
printf("%d\n",a1);
printf("%d\n",a1);
return 0;
}


结果   20
           5307168//这个数每次运行结果都不一样

为什么两次的结果不一样?
为什么a都不存在了还能通过引用输出一次20,第二次输出结果就成了一个不固定的数???求解答,非常感谢

大家讲道理大家讲道理2768 days ago542

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:24:21

    Both outputs are undefined behavior, because the return value of the function is a reference to a local variable, and the local variable will be destroyed when the function ends, so using the returned reference outside the function is undefined. As for the first output of 20, it may have something to do with the compiler. Different compilers handle undefined behavior differently. If you change the compiler, it may output random numbers twice.

    reply
    0
  • Cancelreply