1

I keep getting an error message in CodeBlocks it says:

Error: 'Addnumbers' was not declared in this scope

I just started with C++ and have no idea what this means. Here is my code:

#include <iostream>
using namespace std;

int main()
{
    int fnum;
    int snum;

    cout << "Enter First number" << endl;
    cin >> fnum;
    cout << "Enter Second Number" << endl;
    cin >> snum;

    Addnumbers (fnum, snum);
    return 0;
}

int Addnumbers(int fnum, int snum){
    int ans = fnum+snum;
    return ans;
}

2 Answers 2

2

You need to declare the function before it's used:

int Addnumbers(int fnum, int snum);

int main()
{
}

int Addnumbers(int fnum, int snum)
{
    // ...
}

The first declaration is what is called a prototype, and tells the compiler that somewhere there is a function named AddNumbers with the specified arguments and return type. Then you can have the definition anywhere, even in another source file.

In C++ (as well as in C or other languages base on C) everything must be declared before it it used. That's how the compiler will know that stuff exists.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks A lot! I didn't know. Is this the same for all function? is the Main function ALWAYS last?
@Col1107 Like in my example, the declaration can be before the main function, they just have to be before they are used. However, placing main last is almost always a safe bet.
1

You need to either move Addnumbers before main, or to do a forward declaration:

#include <iostream>
using namespace std;

int Addnumbers(int fnum, int snum);

int main()
{

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.