I have a very basic question, I don't know it was asked before or not? I have tried to find the answer but could not get it.
I am using C++ with different IDEs, like Visual Studio 2019, code blocks, Dev C++ and online compiler named as OnlineGDB.
I have simple code here.
#include <iostream>
int* getInt(){
int x = 10;
return &x;
}
int main()
{
int *ptr = getInt();
std::cout<<*ptr;
return 0;
}
As we know x is a local variable in getInt and when getInt function finish x will be destroyed by the concept of local scope. I am returning reference of x and storing in a pointer which is in main. Now by the book it should not print anything or a garbage value because x is destroyed.
But when I run this code in different IDE they gives different results. Lets see the results.
In OnlineGDB:
warning: address of local variable ‘x’ returned [-Wreturn-local-addr].
It shows this warning and does not print any thing.
In Dev-C++ 5.7.1:
warning: address of local variable ‘x’ returned [-Wreturn-local-addr].
It shows this warning but also print the value 10.
In code blocks:
warning: address of local variable ‘x’ returned [-Wreturn-local-addr].
It shows this warning but does not print any thing.
In Visual Studio 2019: It does not show any warning and print the value 10.
So what is actually happening under the hood, what am I missing? Why same code have different results in different environment.
Aucun commentaire:
Enregistrer un commentaire