Erik Carstensen
Erik Carstensen

Reputation: 888

Expressing a pointer to a const function

In C, I can express a pointer to a const function like this:

typedef void fun_t(void);
const fun_t *fp;

(I don't know if the type of fp has any practical use, but it is a real and distinct type; e.g., the declaration void (*f)(const fun_t *fp); is valid, and initializing that variable with (void (*)(fun_t *fp))NULL is invalid C)

In C23 or GCC, I found that you can express this type without a typedef, using typeof:

const typeof(void (void)) *fp_c23;

Is there a way to express the type more directly, using neither typedef nor typeof?

Upvotes: 0

Views: 60

Answers (1)

KamilCuk
KamilCuk

Reputation: 141698

void (*const fp)(void); has been used for decades.

the declaration void (*f)(const fun_t *fp); is valid

The const there is a GCC extension, it is not valid C and not valid C23 and const typeof(void (void)) *fp_c23; is also not valid. If you look at your error message:

<source>:5:7: note: expected '__attribute__((const)) void (*)(void)' but argument is of type 'void (*)(void (*)(void))'

const is interpreted as GCC extension __attribute__((const)). See https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html . If you compile in pedantic, you'll see:

warning: ISO C forbids qualified function types [-Wpedantic]

Bottom line, if you want a pointer to a void (void) function with const GCC attribute, you would just declare it normally too in GCC.

__attribute__((const)) void (*fp1)(void);
const void (*fp2)(void);

Side note, a function with const attribute returning void doesn't make much sense.

Upvotes: 1

Related Questions