Home > Net >  Undeclared identifier - C VS 2019
Undeclared identifier - C VS 2019

Time:11-03

void print_vector(std::vector<int> vector)
{
    for (int i = 0; i < vector.size(); i  );
    {
        std::cout << vector[i] << "\t";
                            ^ error here**
    }
    std::cout << "\n";
}

I feel like “i” has already been declared. Why is there an error?

Severity    Code    Description
Error       C2065   'i': undeclared identifier

CodePudding user response:

You had a semicolon after the for loop. After you remove this semicolon the code will work as expected.

void print_vector(std::vector<int> vector)
{
    for (int i = 0; i < vector.size(); i  )//;REMOVED THIS SEMICOLON
    {
        std::cout << vector[i] << "\t";
                            
    }
    std::cout << "\n";
}

CodePudding user response:

for (int i = 0; i < vector.size(); i  ); // <-- note the unnecessary semicolon.
{
        std::cout << vector[i] << "\t";
}

The compiler will understand this as:

for (int i = 0; i < vector.size(); i  )
{
     ; // <-- this is now a null statement
}
// this is the end of the loop scope, therefore i is destroyed
{
    std::cout << vector[i] << "\t"; // so no i is declare here, so an error
}

So, you should remove the semicolon.

  • Related