:: Re: [DNG] Making sense of C pointer…
Pàgina inicial
Delete this message
Reply to this message
Autor: karl
Data:  
A: dng
Assumpte: Re: [DNG] Making sense of C pointer syntax.
Steve Litt:
...
> Years ago I gave up trying to logically explain the syntax of function
> pointers, which are so essential for callbacks and pseudo-oop, and just
> memorized the idiom.
>
> Edition 1 of K&R had an actual algorithm by which one could dissect any
> lvalue (thing that can appear on the left of the equal sign), but it
> was so complicated I couldn't understand it. So I memorized the idiom
> for function pointers.
>
> I think C would have been much more successful (and it's already been
> quite successful) if it could have had a better syntax for function
> pointers.


Too late to change that, but I think you are better off if you do a
typedef first, as in:

typedef int (*func_t)(int,int);
int add(int a, int b) {
return a + b;
}

int proc(func_t f, int a, int b) {
return f(a,b);
}

int main(void) {
int ix = 0;

func_t func_arr[10];
func_arr[0] = add;

return proc(func_arr[ix], 1, 2);
}

$ gcc -Wall a.c
$ ./a.out
$ echo $?
3

> I think the reason you see so few callback functions in
> average C code is the syntax,


Just because c gives you the possibility to make code that looks like
tty noise, doesn't mean you have to...

> as well as the unforgivingly strict typing
> of the arguments.

...

The strict typing comes with the language, but you can get around it
with pointers (gives you 0 to x number of arguments, same type unless
the type is void). You can use varargs, and a remote possibility is
to pass down a string and parse it which is quite radable from the
calling side :)

Regards,
/Karl Hammar

-----------------------------------------------------------------------
Aspö Data
Lilla Aspö 148
S-742 94 Östhammar
Sweden
+46 173 140 57