You can do this a bunch of ways, here's one more.
Code:
#include <iostream>
#include <cstring>
using namespace std;
char *retvar()
{
char *ret = new char[sizeof("retvar")];
return strcpy( ret, "retvar" );
}
int main()
{
char *string = retvar();
cout<< string <<endl;
delete string;
return 0;
}
And another that's closer to what you posted but not as handy as other ways.
Code:
#include <iostream>
using namespace std;
char *retvar()
{
return "retvar";
}
int main()
{
cout<< retvar() <<endl;
return 0;
}
And if you want to return multiple values it's best to either use pointers for your parameters or pass a struct with all of the variables you want to return.
harryP, neither of your suggestions will work because both still try to return a local variable, this variable is destroyed when the function returns and main ends up with garbage. You also can't use the same name retvar for everything or the compiler will panic since it has no idea what you want when you say retvar.