Reputation: 23
I'm making an endless text based game in C++ and have multiple functions that need to be able call eachother. I don't seem to be able to do this, because functions need to be defined above where they are called to work, and I can't have them both defined above eachother. How do I make it able to call a function defined below it?
I've tried moving the definition of the functions above eachother, but since one of them needs to call a function defined below it, it won't work.
#include <iostream>
void function_one()
{
int user_selection = 0;
std::cout << "Enter \"1\" to call function 2.\n";
switch (user_selection) {
case 1:
function_two();
break;
}
}
void function_two()
{
int user_selection = 0;
std::cout << "Enter \"1\" to call function 1.\n";
switch (user_selection) {
case 1:
function_one();
break;
}
}
int main()
{
function_one();
return 0;
}
I'm using MS Visual Studio 2019, and the error I get is "C3861 'function_one': identifier not found."
Upvotes: 2
Views: 5656
Reputation: 395
You can put your functions inside class. Then create object of that class. And call your functions on that object. Like this:
#include <iostream>
class SomeName{public:
void function_one()
{
int user_selection = 0;
std::cout << "Enter \"1\" to call function 2.\n";
switch (user_selection) {
case 1:
function_two();
break;
}
}
void function_two()
{
int user_selection = 0;
std::cout << "Enter \"1\" to call function 1.\n";
switch (user_selection) {
case 1:
function_one();
break;
}
}
} someName;
int main()
{
someName.function_one();
return 0;
}
Upvotes: 0
Reputation: 24107
Simply declare the functions on the top, and then you can define them later:
#include <iostream>
void function_one();
void function_two();
int main()
{
function_one();
return 0;
}
void function_one()
{
int user_selection = 0;
std::cout << "Enter \"1\" to call function 2.\n";
switch (user_selection) {
case 1:
function_two();
break;
}
}
void function_two()
{
int user_selection = 0;
std::cout << "Enter \"1\" to call function 1.\n";
switch (user_selection) {
case 1:
function_one();
break;
}
}
Upvotes: 6