Lucas Saito
Lucas Saito

Reputation: 63

Function that returns a pointer in C++

I've started learning about pointers and I ended up with a question over functions and pointers. I created a simple function that should return the address/pointer of an Integer type. However, after printing the address using "&" it differs from what the function returns me. What am I missing here?

int* address_ofInt(int a) {
        return &a;
}
int main() {
        int foo = 124;
        std::cout << &foo << std::endl;
        std::cout << address_ofInt(foo) << std::endl;

        return 0;
}
// It outputs
// 0x7ffee2434b08
// 0x7ffee2434acc

Upvotes: 2

Views: 1030

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

int* address_ofInt(int a) {

This is called "passing by value" in C++. This means that whatever the caller passes, as a parameter to the function, effectively a copy is made, and that's what this a is. This function can modify this a, and it will have no effect on the original parameter, since it's just a copy.

This a is a completely independent object or variable, and its address is completely different and has nothing to do with the address of whatever was passed to this function.

 return &a;

This function returns the address of its by-value parameter. Which is completely meaningless, since once the function returns its by-value parameter no longer exist. It was a copy of the original parameter that was passed to this function, and it gets automatically destroyed. It is no more. It ceased to be. It joined the choir invisible. It's pining for the fjords. It is an ex-variable. The caller gets a pointer to a destroyed object, and attempting to dereference the pointer results in undefined behavior.

Your C++ textbook will have a chapter that explains what references are, how they work in C++, and how to pass parameters to the function by reference instead of by value. And in that case modifying a will actually modify the original object that was the parameter to this function. If you do that you will discover that both pointers will be the same, since the function parameter will be a reference to the original parameter that was passed to it. See your C++ textbook for more information.

Upvotes: 7

Related Questions