调用函数没有参数,括号 [英] Call function without parameter and parenthesis

查看:111
本文介绍了调用函数没有参数,括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下code段,主要功能调用foo函数不带任何参数和括号。奇怪的是,这个code可以通过GCC编译。其实我检查装配code和发现,编译器只是忽略此行。所以我的问题是在何种情况下这种code的使用?或GCC的支持仅仅是一个巧合,其实这是完全没有用的。

  INT美孚(INT A,INT B)
{
    返回A + B;
}
诠释的main()
{
    富; //调用foo没有参数,括号
    返回0;
}

其组装code。通过objdump的-d

  00000000004004c0<主计算值:
  4004c0:55推%RBP
  4004c1:48 89 E5 MOV%RSP,RBP%
  4004c4:B8 00 00 00 00 $ MOV为0x0,%eax中
  4004c9:5D流行%RBP
  4004ca:C3 retq
  4004cb:0F 44 1F 00 00 nopl为0x0(RAX%,%RAX,1)


解决方案

这是没有比拥有任何其他类型的前pression的,而忽略它的价值,就像不同的:

  INT主要(无效)
{
  42;
  返回0;
}

有什么特别,这是的的调用,因为函数调用操作功能()不被使用。所有你正在做的是计算功能的地址,然后忽略它。

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)

解决方案

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.

这篇关于调用函数没有参数,括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆