Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function call with different semantics

Tags:

c

function

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.

like image 400
abc Avatar asked Jun 24 '12 17:06

abc


1 Answers

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.

like image 170
Oliver Charlesworth Avatar answered Sep 25 '22 02:09

Oliver Charlesworth