cparameter-passingconst-correctnessconst-pointer

Meaning of const pointers as function parameters


I have this function signature:

void myFunction(int *const ptr);

What's the point of the const keyword in this particular context?

Even if ptr wasn't a const variable, I couldn't modify to what address it points to, because it's passed by value, so if I had another function like this:

void myAnotherFunction(int *ptr);

And inside its implementation did something like this:

//...
ptr = malloc(1023);
//...

This wouldn't affect the passed value (outside this function, of course).

So the question is: what's the point of using myFunction() signature instead of myAnotherFunction() one? (beside that you get a compile-time error).


Solution

  • ptr = malloc(1023); This wound't affect the passed value (outside this function, of course).

    To sum up. Indeed that way original pointer would not be affected (it would still point to same object because ptr is copy of the original pointer), but you can still make that pointer point to a different object inside myAnotherFunction and change value of that object through that pointer. e.g. in myAnotherFunction you could do:

    ptr = &y;
    *ptr = 9;
    

    Whereas in the first case when you have a constant pointer, you can't assign a new address to it, but you can still change the value of object to which it points using dereferencing. A constant pointer means you can't assign a new address to it, pointer to a constant object means you can't change value of object to which it points, but you can assign new address to the pointer.