Reputation: 4273
I am trying to understand C function pointers. I made this example to describe what I do not understand about the syntax
specifically.
//somewhere in a .h
void(*func_pointer)(int i);
//somewhere in a .c
void func_test(int i)
{
printf("%d\n", i);
}
//initializing the func_pointer
func_pointer = &func_test;// works as expected
func_pointer = func_test;//why this works ? left: pointer, right: function
func_pointer = *func_test;//why this works ? left: pointer, right: ?
//calling the func
(*func_pointer)(2);//works as expected
func_pointer(2);//why this works ? calling a pointer ?
Why is this syntax accepted ?
Upvotes: 2
Views: 158
Reputation: 281
func_pointer = func_test
and func_pointer = *func_test
work because function names are automatically turned into function addresses when used in this context.
func_pointer(2)
works because function pointers automatically dereference themselves, much like references. As to why they do these things, I don't know. Maybe it was decided the syntax was complicated enough already.
Upvotes: 2