0

While reviewing code, I occasionally see function prototypes with constant pointers like:

void Foo(int * const bar);

Often a programmer using such a function does not understand what he actually sees and the function is later used like this:

const int bla = 0;
Foo((int* const) &bla);

which, as far as I understand, results in undefined behavior. In this case, the constant pointer caused confusion.

My question is: When is a constant pointer (not a pointer to a constant) in a function prototype required for the code to be correct?

Paul R.
  • 678
  • 5
  • 19
  • It lets you identify errors at compile time by making modifying `const` pointers as an error – Inian Nov 21 '19 at 10:50

1 Answers1

0

The const keyword is just used to avoid mistakes generating compilation errors if the variable is touched and to optimize code making the assumption that the variable does not change. It is never required. It also is of no interest at all to the caller, since C passes all parameters by value.

Both the usages of const, either const int * or int * const, are just a contract between the programmer and the compiler. They are never required.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128