Pointers as Functions Returns in C/C++
Notes
Let’s look at this code right here, that uses
#include <iostream>
using std::cout;
using std::endl;
int Add(int a, int b)
{
// Called Function
cout << "Address a in Add = " << &a << endl;
int c = a + b;
return c;
}
int main()
{
// Calling Function
int a = 2, b = 4;
cout << "Address a in main = " << &a << endl;
// Call by Value
int c = Add(a,b); // Value of a of main is copied to a of Add
// Value in b of main is copied to b of Add
cout << "Sum = " << c << endl;
return 0;
}
Output
Address a in main = 0x7ffee1a35608
Address a in Add = 0x7ffee1a355dc
Sum = 6
We can see that the a in Add and the a in main are not the same as we print the addresses of the a’s. Which means these variables are not the same, they’re at different memory addresses.
The names of variables are local or specific to a particular function
Passing the Addresses
Lets pass the addresses of a and b to the Add function
#include <iostream>
using std::cout;
using std::endl;
int Add(int* a, int* b)
{
// Called Function
// a and b are pointers to integers
cout << "Address a in Add = " << &a << endl;
cout << "Value in a of Add (address of a of main) = " << a << endl; // Should give address of a in main
cout << "Value at address stored in a of Add = " << *a << endl;
int c = (*a) + (*b);
return c;
}
int main()
{ // Calling Function
int a = 2, b = 4;
cout << "Address a in main = " << &a << endl;
// Call by Value
int c = Add(&a,&b); // a and b are integers local to main
cout << "Sum = " << c << endl;
}
Output:
Address a in main = 0x7ffeeb23e60c
Address a in Add = 0x7ffeeb23e5d8
Value in a of Add (address of a of main) = 0x7ffeeb23e60c
Value at address stored in a of Add = 2
Sum = 6