Reputation: 11929
Considering this code with 3 differents function call semantics:
void f(void){
puts("OK");
}
int main(void){
f();
(*f)();
(&f)();
return 0;
}
The first is the standard way to call f,
the second is the semantic for dereferencing function pointers,
but in the third I'm applying the & operator to the function name and it seems to work fine.
What does in the second and third case happen?
Thanks.
Upvotes: 5
Views: 630
Reputation: 39164
In the second case you are using a function pointer. Function pointers are used to memorize a reference to a function, and be able to call it elsewhere in your call. They are typically used to implement callbacks. So if you have store a pointer to a function you should use the first notation.
I thinkg the first and the third are equivalent. In fact if you declare a function pointer you can initialize it both the following ways:
void AFunction();
void (*funcPtr)() = NULL;
funcPtr = AFunction;
funcPtr = &AFunction;
Upvotes: 1
Reputation: 272517
Function calls are always performed via function pointers. From C99 section 6.5.2.2:
The expression that denotes the called function shall have type pointer to function.
However, in almost all cases a function type decays to a function-pointer type. From C99 section 6.3.2.1:
Except when it is the operand of the
sizeof
operator or the unary&
operator, a function designator with type "function returning type" is converted to an expression that has type "pointer to function returning type".
So your three calls are evaluated thus:
(&f)();
(&(*(&f)))();
(&f)();
All are valid. But obviously, the first one (f()
) is the cleanest and easiest to read.
Upvotes: 8