Unable to detect error in following C++ program:

I have written the following C++ program:

#include <iostream>
using namespace std;

string s1 = "Hello";

int main() {
        string s2 = "World";
        cout << s1 << " " << s2 << endl;
        int s1 = 46;
        cout << s1 << " " << s2 << endl;
        cout << "hello" " " "mars" << endl;
        message();
        return 0;
}

void message(void) {
        cout << s1 << " World" << endl;
}

The compiler is showing me the following error:

24.cpp:12:2: error: ‘message’ was not declared in this scope
  message();

But I have always used function like this. I declared and defined the message() function outside main() function and called it in main() function.

So where am I going wrong?

2 answers

  • answered 2017-11-12 20:15 SourceOverflow

    At the point that you are using message it is not declared. You can resolve this by moving message above main or via forward declaration.

    void message(void);
    
    int main() {
      …
    

  • answered 2017-11-12 20:15 imvpn22

    Just a little change and it will be okay

    #include <iostream>
    using namespace std;
    
    /* Declare the function first */
    void message();    
    
    string s1 = "Hello";
    
    int main() {
            string s2 = "World";
            cout << s1 << " " << s2 << endl;
            int s1 = 46;
            cout << s1 << " " << s2 << endl;
            cout << "hello" " " "mars" << endl;
            message();
            return 0;
    }
    
    void message(void) {
            cout << s1 << " World" << endl;
    }
    

    I think you understand!