Archived

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

Function question!

This topic is 6161 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Declare all the functions at the start of your cpp file, then create them further down.

Like this:


void hi1();
void hi2();

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

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

Be careful; This code will create an infinte loop.

Share this post


Link to post
Share on other sites
Hi. What you need is a function declaration. These are lines that tell the compiler that there is a particular function in the file and it should just wait to see it.

// declare hi1
void hi1();
// declare hi2
void hi2();

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

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

Now the code will compile and the program will run...forever! This code has no way to stop calling itself!

Pete

Share this post


Link to post
Share on other sites