Anjan Anjan - 4 months ago 6
C++ Question

Why doesn’t compile my code?

When I compile my following code on Ubuntu 14.04 GCC compiler, I got below error,

error: ‘add’ was not declared in this scope
cout<<"Add : "<<add(3, 4)<<endl;


Please, help me.

My code is here:

#include <iostream>
using namespace std;

int main()
{
cout<<"Add : "<<add(3, 4)<<endl;
return 0;
}

int add(int x, int y)
{
return x + y;
}

Answer

add either needs to be prototyped before main:

#include <iostream>

int add(int x, int y);

int main()
{
    std::cout<< "Add : "<<add(3, 4)<< '\n';
    return 0;
}

int add(int x, int y)
{
    return x + y;
}

or defined before main:

#include <iostream>

int add(int x, int y)
{
    return x + y;
}

int main()
{
    std::cout<< "Add : "<<add(3, 4)<< '\n';
    return 0;
}

Your compiler hasn't resolved this symbol (i.e., the name of your function) before main is compiled, so it throws an out-of-scope error.