How to use unnamed function arguments in C or C++

2020-04-02 09:43发布

How do I use function arguments declared like

void f(double)
{
    /**/
}

if it is possible?

5条回答
Emotional °昔
2楼-- · 2020-04-02 09:44

The parameter may still get placed onto the stack, so you may be able to find it there (see comments below)

For example only (highly non-portable)

#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);
}

I'm not sure why you'd want to do this though

查看更多
Juvenile、少年°
3楼-- · 2020-04-02 09:45

No. You have to give it a name. I.e.

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

or if you are using iostreams:

void f(double myDouble)
{
    cout << myDouble * 2;
}
查看更多
走好不送
4楼-- · 2020-04-02 09:58

Here is one good link

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

Sometimes though, the above approach is not just used to support legacy code, but also to make sure an overloaded function gets picked, perhaps a constructor. In other words, passing an additional argument just to make sure a certain function gets picked. As well, during code development it might help to use an unnamed argument if, for instance, you write stubs for some routines.

When possible, it probably should be argued that unused parameters should be removed completely both from the function and from all the call points though, unless your specifically trying to overload operator new or something like that.

查看更多
家丑人穷心不美
5楼-- · 2020-04-02 09:59

I hope an example can provide some help:

// 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";
}
查看更多
做个烂人
6楼-- · 2020-04-02 10:05

Compiler will pass 0 by default....its the way we used to distinguish postfix increment operator and we never have to use the actual value passed..

查看更多
登录 后发表回答