Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 830
bilserial Avatar asked Oct 03 '15 18:10

bilserial


People also ask

What is const function parameter?

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.

Why do you use pointers as parameters to functions?

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.

What does const pointer mean?

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.

What does const pointer mean in C?

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.


1 Answers

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.

like image 80
Chris Beck Avatar answered Sep 22 '22 05:09

Chris Beck