Function declaration in function definintion

Is it legal C++ to have a function declaration in function definition?

Upvotes: 0

Views: 184

Answers (3)

Omnifarious
Omnifarious

Reputation: 56128

Yes, it is. Though this question would've been easy to answer. You could've just tried it and seen. In fact, the fact you can do this is one of the sources of an interesting C++ error:

class A {
 public:
   operator int() const { return 0; }
};
void joe()
{
     // Initializing an int?
     int fred(A());
}

Upvotes: 3

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507433

It's legal both as a declaration in the immediate block scope, and as a function definition as a member function of a local class.

void f() {
  // this declares the function defined below (enclosing namespace)
  void g();
  g();
}

void g() {
  struct {
    void help() { ... }
  } h;
  h.help();
}

Upvotes: 4

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272832

Yes, it is legal.

Referring to the C++ spec, a the body of a function definition (8.4) contains a compound-statement, which in turn (6.3) contains one or more statements, one of which can be a declaration-statement.

Upvotes: 1

Related Questions