I accidentally caught myself using two different styles for defining C function pointers in different places and decided to write a minimal program to check for these differences.
These two styles:
int (comp (int))
and
int (*comp)(int)
I wrote a minimal program that uses both of these styles for the same function pointer, one to declare a function and one to define the same function, to see what the compiler has to say about it.
Declaration:
int a_or_b (int (*a_fn)(), int (b_fn()), int (*comp)(int));
Definition:
int a_or_b (int (a_fn()), int (*b_fn)(), int (comp(int))) { int out = a_fn (); if (comp (out)) out = b_fn (); return out; }
As you can (hopefully) see, I used the int (*a_fn)() style for the first parameter in the declaration, and I used the int (a_fn ()) style in the function definition. I am doing something similar with the following two arguments.
I suggested that these may be incompatible types, that these styles may be the difference between passing by reference and assigning a variable to a variable, but when I compiled this program, the compiler silently and happily compiled it, There are no errors, no warnings, nothing.
Since I saw so many textbooks on the second style, while I personally prefer the first style for aesthetic purposes, I am interested in what is the difference between the two styles and which is recommended.
Full code example:
#include <stdio.h> int a (); int b (); int a_or_b (int (*a_fn)(), int (b_fn()), int (*comp)(int)); int a () { return 1; } int b () { return 2; } int comparison (int param) { return param; } int a_or_b (int (a_fn()), int (*b_fn)(), int (comp(int))) { int out = a_fn (); if (comp (out)) out = b_fn (); return out; } int main (int argc, char **argv) { printf ("%i\n", a_or_b (a, b, comparison)); return 0; }
c pointers function-pointers
Marcus harrison
source share