What scenario might require the use \ need of const pointer to (non-const\const) data

61 Views Asked by At

I understand the concept of final in Java or const in C++ for forcing constant values and allowing the compiler to enforce that on anyone using the modules you write.

I am not able to see where would you want to have a const pointer, why would you not want the pointer to change regardless of the data being constant or not:

e.g

why this?

char greetings[] = "Hello";

char * const p = greetings;  // const pointer, non-const data

const char * const p = greetings; // const pointer and const data

I cannot visualize an exmaple where you want to keep the pointer const, could it be for a file handle or something similar? or just a pointer to an object you don't want to change?

1

There are 1 best solutions below

0
On BEST ANSWER

You may want to make a pointer itself constant for several reasons:

  • Helping others understand your code - When you declare a pointer and make it constant, you tell the readers that there are no changes done to that pointer in the rest of your function, so they would have a better idea of how you use the pointer.
  • Helping others maintain your code - Someone else who maintains your code after you will have better idea of what you expected to do with the pointer. If he tries to pass a non-constant reference or a pointer to the pointer that you declared const, the compiler is going to catch this error.
  • Enable compiler optimizations - When compilers see something declared const, they can optimize more aggressively.