Skip to content

/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

main.cpp
#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

cpp
#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

NameHeader
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