Norman Norman - 1 year ago 99
C++ Question

C++ problematic code piece

We got practice sheets for a test next week, for studying a little bit of C++ (still a beginner here). I still can't figure out a simple question.

That is, why are these snippets of code problematic?

int& p(int z) { return z; }
int* h(int z) { return &z; }

Answer Source

When int *h(int z) {return &z} is called, the parameter passed to the function is copied to a variable named z. That copy only lasts as long as the function. So once the function returns, it is no longer available to your program. So you can't have a valid pointer to it once the function returns: formally &z is invalidated.

The same is true for the reference version int &p(int z) {return z}.

As an exercise, see if you can figure out what would happen if z was itself a reference: i.e. int &p(int& z) {return z}. Then, a copy would not be taken. But do note that no professional would ever write a function like this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download