Hey folks! I'm a bit puzzled about function pointer syntax in C and could use some help. I understand that `int (*func)(int);` defines a pointer to a function named `func` that takes an integer and returns an integer. However, I'm confused about why this syntax: `int (*func(int));` is incorrect. To me, it seems the `*` is still relating to `func(int)`. I initially thought that this could define a function that takes an integer and returns a `void *`, but then I'm not sure what the first `int` implies. If it's interpreted at the end, would it be equivalent to declaring `int * func(int)` instead? Thanks a bunch for any clarity you can provide!
3 Answers
For decoding C declarations, check out cdecl.org! It'll make understanding these syntaxes a lot easier. For instance, `int (*f)(int)` means `f` is a pointer to a function returning an int, while `int (*f(int))` defines `f` as a function returning a pointer to int, which is a key difference.
If you're looking for a full rundown on function pointers, GeeksforGeeks has some solid explanations. It might take some practice to differentiate between function pointers and regular functions, but once you get used to it, it becomes clearer!
After digging into those resources, it seems I was overcomplicating things! It’s actually not as hard as it looked. Appreciate the help!
The reason `int (*func(int));` is incorrect is due to how C interprets function declarations. In this case, `int (*f(int))` declares `f` as a function taking an int and returning a pointer to an int, rather than a pointer to a function. Keeping track of the `*` placement can be tricky! You might want to check out Cprogramming.com for more insights on the topic.
Thanks for that resource! I tried some code with `typedef bool (*CharPredicate(char));` and surprisingly, my editor showed the type as `bool (*(char))`. No errors came up either. What’s up with that?
That tool is fantastic! I’ll definitely use it again, thanks for the tip!