Search code examples
c++pointerslocal-variables

C++ - Pointer to local variable in Google's exercise code


Here, in Exercise #1, there is a function HardToFollow:

void HardToFollow(int *p, int q, int *num) {
    *p = q + *num;
    *num = q;
    num = p;
    p = &q;
    Unknown(num, *p);
}

The second last line makes p point to q which is a local variable(copy of an argument). A pointer to a local variable.

Later, in the main function, the pointer passed as this first argument is used after the call. Shouldn't this be undefined behaviour? Shouldn't the pointer passed as the first argument be undefined after a call to HardToFollow()?

Edit: I understood that it's not undefined behaviour, the pointer itself can be changed without reflecting the behaviour to the passed argument, only the changes to the pointed value will be permanent.


Solution

  • Remember that all arguments by default are passed by value. That means the value of the passed expression is copied into the functions local argument variable. That also means that changing the argument variable (like say assigning to it) will only change the local argument variable itself, not the original value used when calling the function.

    This is what happens here: Someone calls the HardToFollow function passing a pointer. The value of this pointer is copied into the local argument variable p. And any assignment to p itself will only modify the local variable p.

    So no this doesn't lead to UB, it's perfectly valid.