Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function without parameter and parenthesis

Tags:

c

In the following code snippet, the main function calls foo function without any parameter and parenthesis. It is strange that this code can be compiled by gcc. I actually check the assembly code and find out that the compiler just ignore this line. So my question is in which situation this kind of code is used? Or the support of gcc is just a coincidence and actually it is totally useless.

int foo(int a,int b)
{
    return a+b;
}
int main()
{
    foo;      // call foo without parameter and parenthesis
    return 0;
}

Its assembly code dumped by objdump -d

00000000004004c0 <main>:
  4004c0:   55                      push   %rbp
  4004c1:   48 89 e5                mov    %rsp,%rbp
  4004c4:   b8 00 00 00 00          mov    $0x0,%eax
  4004c9:   5d                      pop    %rbp
  4004ca:   c3                      retq   
  4004cb:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)
like image 422
coinsyx Avatar asked Dec 14 '12 15:12

coinsyx


2 Answers

This is no different than having any other type of expression and ignoring its value, like:

int main(void)
{
  42;
  return 0;
}

there's nothing special, this is not calling the function since the function-call operators () are not being used. All you're doing is "computing" the functions' address, then ignoring it.

like image 78
unwind Avatar answered Nov 02 '22 05:11

unwind


The expression foo is evaluated (giving the address of the function), and the result is discarded. Without the () operator, the function isn't called.

like image 7
John Bode Avatar answered Nov 02 '22 04:11

John Bode