Search This Blog

Sunday, July 5, 2009

C++ Returning Local Variable As Reference is Bad

#include

int& returnLocalReferenceIsBad()
{
int localVariable = 5; //local variable on the stack
//, so it will be deleted after return

return localVariable; //return the local variable,
//but, it is BAD,
//AS REFERENCE (Note the function signature)
}

int main(int argc, char *argv[])
{
using namespace std;
int test = returnLocalReferenceIsBad();
//variable test is undefined~
}

No comments: