【问题标题】:How to use unnamed function arguments in C or C++如何在 C 或 C++ 中使用未命名的函数参数
【发布时间】:2010-03-22 07:00:06
【问题描述】:

如何使用声明为

的函数参数
void f(double)
{
    /**/
}

可以吗?

【问题讨论】:

  • 。只需添加一个不会破坏先前声明的名称

标签: c++ function arguments


【解决方案1】:

希望一个例子能提供一些帮助:

// Declaration, saying there is a function f accepting a double.
void f(double);

// Declaration, saying there is a function g accepting a double.
void g(double);

// ... possibly other code making use of g() ... 

// Implementation using the parameter - this is the "normal" way to use it. In
// the function the parameter is used and thus must be given a name to be able
// to reference it. This is still the same function g(double) that was declared
// above. The name of the variable is not part of the function signature.
void g(double d)
{
  // This call is possible, thanks to the declaration above, even though
  // the function definition is further down.
  f(d);
}

// Function having the f(double) signature, which does not make use of 
// its parameter. If the parameter had a name, it would give an 
// "unused variable" compiler warning.
void f(double)
{
  cout << "Not implemented yet.\n";
}

【讨论】:

  • 这是最好的答案。 +1。
  • @zed91 - 您应该将帮助您解决问题的答案标记为“已接受”。无论投票分数如何,您都可以将任何答案标记为已接受。总是接受你的问题的答案被认为是礼貌的。它还将使您的声望+2,答案的作者+15。
  • 其他用例是传递函数指针和模板。
【解决方案2】:

没有。你必须给它一个名字。 IE。

void f(double myDouble)
{
    printf("%f", myDouble * 2);
}

或者如果您使用 iostreams:

void f(double myDouble)
{
    cout << myDouble * 2;
}

【讨论】:

  • @Alan: varargs.h 以及可变参数语法和支持。
  • @Alan:这个问题同样适用于C或C++,所以我使用了C函数。
  • @Alan:我知道,但这并不意味着其他人不会阅读并发现它适用于其他地方。
  • @Billy:使用%f%g 打印双精度。
【解决方案3】:

这是一个很好的link

void bar(int arg1, int /* Now unnamed */, int arg3)
{
    // code for bar, using arg1 and arg3
}

但有时,上述方法不仅用于支持遗留代码,还用于确保选择重载函数,可能是构造函数。换句话说,传递一个额外的参数只是为了确保某个函数被选中。同样,在代码开发过程中,使用未命名参数可能会有所帮助,例如,如果您为某些例程编写存根。

如果可能的话,应该认为应该从函数和所有调用点中完全删除未使用的参数,除非您特别尝试重载 operator new 或类似的东西。

【讨论】:

    【解决方案4】:

    参数可能仍会被放入堆栈中,因此您可以在那里找到它(参见下面的 cmets)

    仅用于示例非常不便携

    #include<stdio.h>
    void f(double)
    {
        double dummy;
        printf("%lf\n",*(&dummy-2)); //offset of -2 works for *my* compiler
    }
    
    int main()
    {
        f(3.0);
    }
    

    我不知道你为什么要这样做

    【讨论】:

    • 这高度依赖于实现(取决于 CPU、ABI 等)。
    • @Paul R. 这是我对这个问题的解释。至少在OP澄清它之前。我在答案中添加了注释
    • 参数不一定在堆栈上传递。更有可能在寄存器中通过,例如如果使用 SSE2 FP(很有可能)。
    • 我根本看不到这其中的价值。我们真的无法告诉 OP 在哪里可以找到这些数据。如果他有能力搜索它,他就有能力给参数命名。
    • 你不应该在互联网上写下来,这甚至不应该被提及。人们会使用它。
    【解决方案5】:

    编译器默认会传递 0....这是我们用来区分后缀增量运算符的方式,我们永远不必使用传递的实际值..

    【讨论】:

    • 未命名参数与默认值不相关且不相关。除非使用未命名参数声明函数的人也告诉它默认为 0,否则编译器不会“默认传递 0”,并且调用者可以 - 并且必须 - 传递一个特定值,尽管该值是不可用的没有标识符。 operator++operator-- 的边缘情况是设计中的一个不幸缺陷,现在已经确定,但它与所有其他未命名或默认参数的行为方式无关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 2011-02-04
    相关资源
    最近更新 更多