Archived

This topic is now archived and is closed to further replies.

ghostboy

Function question!

Recommended Posts

ghostboy    122
I have 2 functions, and I want them to be able to call to each other, but they''re inside the same .cpp file. I''ll give an example of what I have and what I''d want to do.. void hi1() { cout << "how are you?"; hi2(); } void hi2() { cout << "i am fine." << endl; hi1() } hi2 works fine, but hi1 won''t work because it says hi2 wasnt declared or created yet....so how would i get past this problem??

Share this post


Link to post
Share on other sites
ironfroggy    122
simple. declare them both at the top of the file. you need to declare them anyway if you wanna use them in other modules, at least i do that. im very sure you have to.. makes it easier anyway! best thing to do as i see it, is make a header file and put the declarations in there. include the header in other modules then to use them!

someone please tell me if i have made any mistakes!

Share this post


Link to post
Share on other sites
QWERTY    122
At first you have to declare both your functions like this

void hi1();
void hi2();

Then you write your function definitions as follows

void hi1()
{
cout << "how are you?";
hi2();
}

void hi2()
{
cout << "i am fine." << endl;
hi1()
}

Now you can call hi1() or hi2() without any problems.
By the way it seems you just created an infinite loop here when one function call another forever.

Share this post


Link to post
Share on other sites
Mezz    571

NOTE: My eyes seemed to have decieved me, as QWERTY's reply explained everything in full, and my reply is just a re-statement. Don't know how I could have missed that

QWERTY seems to be explaining the correct solution, although I'm not sure it was quite clear what was meant.

basically, declare the function(s) before definition:

void hi1(); // declares hi1
void hi2(); // declares hi2

Then just define them as you have done.
These declarations give your compiler some "advanced warning" if you like, as to what is coming, and it won't flag any errors (providing it's all correct, of course).

-Mezz


Edited by - Mezz on January 31, 2001 5:30:19 PM

Share this post


Link to post
Share on other sites