Pass by value

Mar 29, 2019 at 9:43am
Hello,

I had a question regarding passing parameters by value into a function, and what exactly happens.

1
2
3
4
5
6
7
8
9
10
11
int* test(int b) {
    b++;
    return &b;    
}
//from main:

int a = 5; //a is stored somewhere in memory
cout << test(a); //in the call we basically say int b = a; i.e. b will be a copy of a stored somewhere else in memory. In the test-function we then increase the value of the b-parameter by one, so if we de-reference the address of b:
cout << *test(a); //the output is 6. 


Is the above correct re. what happens?
Mar 29, 2019 at 9:59am
b will no longer exist after the function has ended so the function will actually return a pointer to a variable that no longer exist. Dereferencing the returned pointer is therefore not safe and there is no guarantees what will happen if you do so.
Mar 29, 2019 at 10:04am
Thanks. Is that due to the scope? I.e. b is created at a new memory location(different from a) when the function is called and then deleted when the function ends?
Last edited on Mar 29, 2019 at 10:05am
Mar 29, 2019 at 10:05am
Yes. b goes out of scope when the test function ends.
Topic archived. No new replies allowed.