Adam Oates Adam Oates - 2 months ago 16
C++ Question

C++ Functions not declared?

I'm trying to make a command line game and I declare these two functions but when I call

playerAttack();
the build message says
error: playerAttack start was not declared in this scope
I declared the functions
playerAttack()
and
cpuAttack()
before the
int main() {...}
function if that helps. Please help thank you in advance.

void cpuAttack() {
if (playerHealth > 0 && cpuHealth > 0) {
cout << "Attack Direction (left, right, or center): ";
cin >> attack;
cout << name << " attacks from the " << attack << endl;
srand(time(0));
cpuBlock = attDir[rand() % 2];
cout << "CPU-1 blocks the " << cpuBlock << endl;
if (attack != cpuBlock) {
cpuHealth - dmg;
} else {cpuHealth = cpuHealth - (dmg + 20);}
playerAttack();
} else if (playerHealth > 0 && cpuHealth <= 0) {
cout << "\n" << name << " has won the game.\n";
} else if (playerHealth <= 0 && cpuHealth > 0) {
cout << "\nCPU-1 has won the game.\n";
}
}


and

void playerAttack() {
if (playerHealth > 0 && cpuHealth > 0) {
cout << "Attack Direction (left, right, or center): ";
cin >> attack;
cout << name << " attacks from the " << attack << endl;
srand(time(0));
cpuBlock = attDir[rand() % 2];
cout << "CPU-1 blocks the " << cpuBlock << endl;
if (attack != cpuBlock) {
cpuHealth - dmg;
} else {cpuHealth = cpuHealth - (dmg + 20);}
cpuAttack();
} else if (playerHealth > 0 && cpuHealth <= 0) {
cout << "\n" << name << " has won the game.\n";
} else if (playerHealth <= 0 && cpuHealth > 0) {
cout << "\nCPU-1 has won the game.\n";
}
}

Answer

Because the two functions are mutually dependent on each other, one of them must already know about the other before that one is defined. The solution is to declare them prior to definition:

void cpuAttack();
void playerAttack();

// now define them ...

Alternatively, you could get rid of the mutual dependence by allowing something else to control the turn-taking, and thus not stacking calls on top of each other (which might in some cases result in a stack overflow).