Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c++ - Is there any use for local function declarations?

Most C++ programmers like me have made the following mistake at some point:

class C { /*...*/ };

int main() {
  C c();     // declares a function c taking no arguments returning a C,
             // not, as intended by most, an object c of type C initialized
             // using the default constructor.
  c.foo();   // compiler complains here.

  //...
}

Now while the error is pretty obvious once you know it I was wondering if there is any sensible use for this kind of local function declaration except that you can do it -- especially since there is no way to define such a local function in the same block; you have to define it elsewhere.

I think that Java-style local classes are a pretty nice feature which I tend to use often, especially the anonymous sort. Even local C++ classes (which can have inline-defined member functions) have some use. But this local function declaration without definition thing seems very awkward to me. Is it just a C-legacy or is there some deeper use case which I am not aware of?

Edit for the non-believers: C c() is not a function pointer declaration.

This program

int main()
{
  void g();
  cout << "Hello ";
  g();
  return 0;
}

void g()
{
  cout << "world." << endl;
}

outputs Hello world. This program

void fun()
{
  cout << "world." << endl;
}

int main()
{
  void g();
  g = fun;
  cout << "Hello ";
  g();
  return 0;
}

does not compile. gcc complains:

error: cannot convert 'void ()()' to 'void ()()' in assignment

comeau:

error: expression must be a modifiable lvalue
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The only use I can think of is to reduce the scope of function declarations:

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

void otherFunc()
{
    doSomething();  // ERROR, doSomething() not in scope
}

void doSomething()
{
    ...
}

Of course, there are much better solutions to this. If you need to hide a function, you should really restructure your code by moving functions into separate modules so that the functions which need to call the function you want to hide are all in the same module. Then, you can make that function module-local by declaring it static (the C way) or by putting it inside an anonymous namespace (the C++ way).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...