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).
Declaring function parameters const indicates that the function promises not to change these values. In C, function arguments are passed by value rather than by reference. Although a function may change the values passed in, these changed values are discarded once the function returns.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.
A constant pointer is one that cannot change the address it contains. In other words, we can say that once a constant pointer points to a variable, it cannot point to any other variable. Note: However, these pointers can change the value of the variable they point to but cannot change the address they are holding.
A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.
It might make more sense if you consider that the function
void myFunction(int *const ptr);
might be manipulating many pointers, and assigning them and reassigning them, and an invariant of the algorithm it is executing is that the input pointer should never be changed. Then, labeling it const
might be very helpful, or at least make you feel more confident that its been implemented correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With