/errors/cpp/was-not-declared-in-this-scope
C++ error: 'x' was not declared in this scope
The commands on this page have not been executed by our verification runner yet.updated
- tool
- C++
- exit code
- 1
- versions
- GCC
- os
- linux, macos, windows
error: 'x' was not declared in this scope is GCC's message for a name it cannot find at that point of the file: no variable, function or type called x has been declared in the current scope or an enclosing one. The usual causes are a missing #include, a missing std:: prefix, a function called before its declaration, or a variable used outside the block where it was declared. Recent GCC versions often add a note: that names the header defining a standard name, or a did you mean suggestion. Clang reports the same problem as use of undeclared identifier 'x'.
Example
#include <vector>
int main() {
std::vector<int> v{3, 1, 2};
sort(v.begin(), v.end()); // <algorithm> not included
cout << v[0]; // missing std:: (and <iostream>)
for (int i = 0; i < 3; i++) { int last = v[i]; }
return last; // last only exists inside the loop
}Fixes
#include <algorithm>
#include <iostream>
#include <vector>
int square(int x); // declare before use (or include its header)
int main() {
std::vector<int> v{3, 1, 2};
std::sort(v.begin(), v.end());
std::cout << v[0] << '\n';
int last = 0;
for (int i = 0; i < 3; i++) { last = v[i]; }
return square(last) > 0 ? 0 : 1;
}
int square(int x) { return x * x; }Name to header
| Name | Header |
|---|---|
| std::cout, std::cin, std::endl | <iostream> |
| std::sort, std::find, std::max | <algorithm> |
| std::string, std::to_string | <string> |
| std::unique_ptr, std::make_shared | <memory> |
| printf, std::printf | <cstdio> |
| strlen, memcpy | <cstring> |
| uint8_t, int64_t | <cstdint> |
Sources
Related pages
errors · cppC++ error: no matching function for call toNo candidate function, constructor or template accepts the argument types you passed. Read the candidate notes, then fix the arguments, overloads or types.errors · cppC++ undefined reference to `function()' (ld returned 1 exit status)undefined reference is a linker error: a function was declared but its definition was not linked. Add the .cpp file or library, fix -l order, or define it.errors · cC error: implicit declaration of function 'foo' [-Wimplicit-function-declaration]C compilers reject a call to a function with no prior declaration; GCC 14 and Clang 16 made it an error. Include the right header or add a prototype first.