error ‘ ‘ was not declared in this scope means the compiler unable to find the declaration of a variable or a function
we have a rule in C/C++ that before you call a variable or a function you should declare them first
it is the job of a compiler to match the variable call or a function call, to its declaration
if the compiler doesn’t find the match between the call and the declaration
then at that instant, it will throw an error such as ‘ variable or a function ’ was not declared in this scope
let’s deconstruct some examples to understand the cause of the error
the compiler didn’t find the declaration of the variable b
#include <iostream> using namespace std; int main() { int a=2; //b=3; //error 'b' was not declared in this scope cout << "addition=" <<a+b<< endl; return 0; }
you can not access a variable from outside of the block
what is a block?
Straightway, a block means an opened and closed braces
{
}
The truth is once the controller comes out of a block, then, at that instant, you can not access the variables that were present in the block
#include <iostream> using namespace std; int main() { { int a=2; b=3; cout << "print variable a=" <<a<< endl; } cout << "print variable b=" <<b<< endl; // error: 'b' was not declared in this scope return 0; }
you can not access a variable from the outside function
#include <iostream> using namespace std; //int b=3;//Global variable void test() // function declaration { cout << "print variable b=" <<b<< endl; } int main() { { int a=2,b=3; cout << "print variable a=" <<a<< endl; } // error: 'b' was not not declared in this scope test();// function call return 0; }
You can not use the functions of the header files until and unless you #include<header>
For example, the header file #include<math.h> contains functions such as
Exp(x)
Floor(x)
Sqrt(x)
Log(x) and so on
The header file <math.h> will have all the build-in declarations for its functions
Straightway, if you use the functions of the math.h undoubtedly the compiler will not be able to find its function declarations
As a result, it will throw an error such as “ ’ ‘ was not declared in this scope”
#include <iostream> //#include <math.h> using namespace std; int main() { int a=2,b=3;//error 'pow' was not declared in this scope if you did not file #include<math.h> cout << "power=" <<pow(a,b)<< endl; return 0; }
You can not access a function call until and unless you declare them first
the compiler didn’t find the declaration of the function test( )
#include <iostream> using namespace std; int b=3;//Global variable /*void test() // function declaration { cout << "print variable b=" <<b<< endl; } */ int main() { { int a=2; cout << "print variable a=" <<a<< endl; } // error: 'test' was not not declared in this scope test();// function call return 0; }
Leave a Reply