c++pointersparameter-passingconst-pointer

Why can't I change address of a pointer of type `const int *` when passed as function argument?


As far as I know, const int * implies that I can change the pointer but not the data, int * const says that I can't change the pointer address but I can change the data, and const int * const states that I can't change any of them.

However, I can't change a address of a pointer defined with the type const int *. Here is my example code:

void Func(const int * pInt)
{
    static int Int = 0;
    pInt = ∬
    Int++;
}

int wmain(int argc, wchar_t *argv[])
{
    int Dummy = 0;
    const int * pInt = &Dummy;
    //const int * pInt = nullptr;   // Gives error when I try to pass it to Func().
    std::cout << pInt << '\t' << *pInt << std::endl;
    std::cout << "-------------------" << std::endl;
    for (int i=0; i<5; i++)
    {
        Func(pInt);     // Set the pointer to the internal variable. (But, it doesn't set it!)
        std::cout << pInt << '\t' << *pInt << std::endl;
    }
     return 0;
}

Code output:

00D2F9C4        0
-------------------
00D2F9C4        0
00D2F9C4        0
00D2F9C4        0
00D2F9C4        0
00D2F9C4        0

I would expect the address of pInt to change to point to the internal variable inside the Func() function after calling Func() for at least once. But it doesn't. I keeps pointing at the Dummy variable.

What is happening here? Why don't I get the result I expect?

(IDE: Visual Studio 2015 Community Version)


Solution

  • You don't see the change at the call site because you are passing the pointer by value. Modifying it inside Func will just change the local copy, not the pointer passed in.

    If you want to modify the pointer and have the changes visible outside, pass it by reference:

    void Func(const int *& pInt)
    //                   ^