Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

c - function call with different semantics

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...