If I write something as follows:
int f(char x, const int (*g) (const char x)) {
return g(x);
}
does the first const
say effectively what I think it says, namely basically that the programmer can't change the code of the function g? So basically, it is a good practice to put those const
s when passing a function pointer as a parameter?
The first const
declares the returned int
to be immutable - but that will not matter since the receiver will copy it into a non-const
int
if that's wanted - which is exactly what your f()
function does. It calls g()
which is declared to return a const int
but f()
returns an int
. The first const
will just be ignored.
It does not have to do with changing the code of g()
. That's not allowed under any circumstances.
If you want to make it clear that the function pointer will not be made to point at another function inside f
:
int f(char x, int (*const g) (const char x))