c++function-pointersconst-pointer

const void (* to function)


Is there any difference between:

void (* const algorithm)();

and

void const (* const algorithm)();

when dealing with const pointers to static methods?

I understand that it would make sense to use const if the pointer points to memory that should not be modified, in case of pointers to variables, as stated in this answer. However, are function addresses not effectively constant during run-time anyway?

The reason I am asking this is, the second option as a function parameter does not work.

EDIT

Here is the code that does not compile.

struct A {
    static void a() {}
};

void b(void const (* const callback)()) {}

int main() {
    b(&A::a); // No matching function for call to 'b'
}

The above example works, if function a() has a return type const void.


Solution

  • const after (or before) the return type applies to the return type. There is no such thing as a "pointer to const function" as there is no such thing as a const function. (Although, there is such thing as a pointer to const member function, as const member functions do exist. But there the constness applies to the object argument, not to the function itself. There the constness is expressed in the same way as in the declaration of a member function - after the parenthesized parameter list).

    There is no difference between void() and void const() in the sense that both functions behave exactly the same because there is no behavioral difference between a const void return type and a non-const void return type. Object cannot be const when there is no object.

    I would expect a compiler to issue a warning when a non-class return value is directly qualified with const.

    However, void() and void const() are different in the sense that void and void const are technically separate types, as are all const qualified types different from their non-const counterpart. Therefore the function pointers to const returning and non-const returning functions are different function pointer types. As such, the standard won't allow a function pointer to one type be bound to a function of another type.

    So, to fix your non-compiling code, simply replace void const which is nonsensical with void in the function pointer.