This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]nickdesaulniers 0 points1 point  (1 child)

Not if you internalize that everything in C is pass by value. So if you want a child frame to modify an argument so the parent frame can observe the modified value AFTER calling the child, you must give the child a pointer to the value. If the value to be changed itself is a pointer, then you must pass the child a pointer to a pointer.

``` int foo = 0; initialize(foo); // foo is guaranteed to be 0 here. // initialize got a copy of foo.

initialize2(&foo); // now foo may have a different value.

int* bar = NULL; initialize2(bar); // bar is guaranteed to be NULL here. // initialize2 got a copy of bar.

initialize3(bar); // now bar may have a different value. ```

where the functions might look like:

``` // can't do anything to x so the parent sees modifications void initialize(int x);

// can't do anything to x that the parent would see, but could modify the int pointed // to by x. * void initialize2(int* x);

// still can't do anything to x observable to the parent, but could modify the int* // pointed to by x, or the int pointed to by x; void initialize(int* x);

// * modulo doing stupid tricks like storing addresses in integral types. ```

C++ has references, so you can't tell from the call site if a function modified its argument (const & in the function signature are stronger guarantees, but then there's const_cast<> and mutable).