Bill Daugherty Bill Daugherty - 2 months ago 14
C++ Question

C++ Beginner. Adding a function and calling it fails

Can you help me and let me know why this is failing? I am getting an error as shown below:

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
#include <conio.h>

int main()
{
int a;
string abc = "";
cout << "Enter your Name\n";
cin >> abc;
cout << "Enter Your Age\n";
cin >> a;
cout << "Hello " << abc << ", it is nice to meet you.\n";

StartPause();

return 0;
}

void StartPause()
{
cout << "\nPress any key to continue..." << endl;
_getch();
}


Severity Code Description Project File Line Suppression State
Error C3861 'StartPause': identifier not found GreetingsConsoleApp \bpm-fs103\users...\greetingsconsoleapp.cpp 20

ray ray
Answer

The compiler processes the compilation unit, your .cpp file in this case, sequentially from top to bottom.

Your StartPause function has been neither declared nor defined by the time the compiler finds a call to it, so it complains. It's analogous to having an undeclared variable.

To solve it, either:

  1. Add a forward function declaration before the definition of main, or
  2. Move the definition of main so that it's at the bottom of the compilation unit

In other words, either this:

// includes and stuff...

void StartPause();  // <-- forward declaration

int main() {
    // body definition
}

void StartPause() {
    // body definition
}

Or this:

// includes and stuff...

void StartPause() {
    // body definition
}

int main() {
    // body definition
}

Any of these two will solve the problem because now the compiler will know what StartPause is before an invocation attempt is made and will know what to do.