Non-Dynamic Local address

Can I return a non-dynamic local address of a var from a function?

int* func(int m){

m=1;

return m;

}

my compiler giving warning but compiles and returns add but My tutor handout says it will not compile...!!! she used array in func and returned arr[m]
You're casting m from an integer to an address, not returning its address.

You can return the address of a local variable, but it will result in undefined behavior. Anything could happen - your computer could explode, your compiler is allowed to reject it, it could install a virus and start up Portal 2, or it might just appear to work and let you overwrite random memory. I'm not kidding.
so to avoid this I can use dynamic local var and return it?
Yes. Or you can retur static variable from functio. Or you can take argument by reference and return address:
1
2
3
4
5
6
7
8
9
10
11
int* func(int& m)
{
    m = 1;
    return &m;
}

int* func()
{
    static m = 2;
    return &m;
}

thanks..bottom line is, return any var which lives after func exit...
Topic archived. No new replies allowed.