Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how higher order functions work in C

So usually I would declare any function pointer like this:

typedef size_t (*hash_function)(const int *);

and then later use it in another function

HashTable *hash_table_create(const hash_function hash)

so for any function which fulfills the hash_function definition like

size_t hash_modulo(const int *parameters)
size_t hash_universal(const int *parameters)
...

I can use them as a parameter

hash_table_create(hash_modulo)

The problem is: My IDE (Clion) complains that the parameters in this case do not match (the code works tho). Specifically it doesn't seem to accept passing hash_function as a parameter type, but will accept if I use size_t (*hash_function)(const int *) instead. What am I missing here?

Is my code right and my IDE wrong or vice versa?

Thanks in advance!

Edit 1: The exact error message is: Types 'hash_function' and size_t(const int *)' are not compatible

Edit 2: This seems to be a Clion Bug

like image 543
AdHominem Avatar asked Feb 17 '26 16:02

AdHominem


2 Answers

CLion seems to have a bug (possibly). The function names are of the type size_t(const int *). Now, since functions are implicitly convertible to function pointers, your code is perfectly valid C.

The CLion syntax checker probably doesn't take implicit conversions into account. If you obtain a function pointer explicitly from the function name the error should go away:

hash_table_create(&hash_modulo); // Note the ampersand
like image 140
StoryTeller - Unslander Monica Avatar answered Feb 19 '26 05:02

StoryTeller - Unslander Monica


I think the problem is that you typedef the function as const

HashTable *hash_table_create(const hash_function hash)

and the other functions you want to put in as parameters aren't declared const

size_t hash_modulo(const int *parameters)
size_t hash_universal(const int *parameters)

Edit:

This works fine in CodeBlocks

Change this:

size_t hash_modulo(const int *parameters)
size_t hash_universal(const int *parameters)

into this:

hash_function hash_modulo;
hash_function hash_universal;

and then this work fine:

hash_table_create(hash_modulo);
hash_table_create(hash_universal);

Explanation in the comment below.

like image 35
Alex Avatar answered Feb 19 '26 06:02

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!