Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

URGENT: function in function

Status
Not open for further replies.

1510982

Programmer
Feb 17, 2002
57
SI
I'm using g++ to compile this function:

void first() {
int sth = 5;
void second() {
printf("%d", sth);
}
second();
}

It outprints an error saying:
ISO C++ forbids declaration of `second' with no type

What is the problem? I'm in a big hurry (tommorow is deadline), so please help.

Regards, Lovro

 
I have never heard before about "function in function". Why do you need it?
 
C++ thinks the function call to second() (within first) is a competing declaration. This is because C++ allows function overloading and thinks you are providing another prototype/declaration.

How else would C++ know you didn't mean to declare another version of "second" which accepted any # of arguments? (The "no type" means the function call to second() doesn't specify any return type).

Compile this with gcc (with a .c extension) and it works because C doesn't have function overloading. Otherwise move the function definition outside the function and call it like a normal person.

If you want to "hide" functions within a scope, use namespaces or proper OOP design instead.

 
functions in functions are non-sencical... You would want to call a function (not delcare a function) in another function.

Code:
int f();
int g(int);

int f()
{
  return g(5);
}

int g(int a)
{
   return a*2;
}

what you want is something like this:
Code:
void first() {
    int sth = 5;
    second();
}

void second(s) {
    printf("%d", s);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top