Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, what is the difference between `&function` and `function` when passed as arguments?

Tags:

For example:

#include <stdio.h>  typedef void (* proto_1)(); typedef void proto_2();  void my_function(int j){     printf("hello from function. I got %d.\n",j); }  void call_arg_1(proto_1 arg){     arg(5); } void call_arg_2(proto_2 arg){     arg(5); } void main(){     call_arg_1(&my_function);     call_arg_1(my_function);     call_arg_2(&my_function);     call_arg_2(my_function); } 

Running this I get the following:

> tcc -run try.c hello from function. I got 5. hello from function. I got 5. hello from function. I got 5. hello from function. I got 5. 

My two questions are:

  • What is the difference between a function prototype defined with (* proto) and one defined without?
  • What is the difference between calling a function with the reference operator (&) and without?
like image 891
brice Avatar asked Jun 09 '11 13:06

brice


2 Answers

There is no difference. For evidence see the C99 specification (section 6.7.5.3.8).

"A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1."

like image 166
Nick Fortescue Avatar answered Sep 19 '22 19:09

Nick Fortescue


There is no difference between &function and function - they're both addresses. You can see this by printing them both:

function bar();   ....  printf("addr bar is 0x%d\n", &bar); printf("bar is 0x%d\n", bar); 
like image 22
Scott C Wilson Avatar answered Sep 20 '22 19:09

Scott C Wilson