为什么我在代码块中遇到编译错误,因为我使用的变量超出了范围?

why i'am getting compilation error in code blocks that i'm using variables out of scope?

本文关键字:变量 范围 代码 遇到 为什么 错误 编译 因为      更新时间:2023-10-16

错误信息代码块

当选择排序时,在调用swap函数时,错误弹出为

**错误:'j'的名称查找更改为ISO作用域**

void selectionsort(int size, int A[]){
    for(int i = 0; i<size -1 ; i++){
        int min =i;
        for(int j=i+1; j<size;j++){
            if(A[min]>A[j])
                {min = j;}
        }
        swap(A[min],A[j]);}
}

您在内部循环的初始化中定义了j,这将其范围限制在该循环中。如果你想在循环之外使用它,你应该在循环之外定义它。例如:

void selectionsort(int size, int A[]){
    for(int i = 0; i<size -1 ; i++){
        int min =i;
        int j; // defined outside the loop
        for (j = i+1; j < size; j++) {
            if (A[min] > A[j]) { // used inside it
                min = j;
            }
        }
        swap(A[min], A[j]); // and outside it
    }
}

变量的作用域是指可以访问它的代码块。你不能在代码块之外访问这个变量。所以,当你在for循环中定义整数j时,你只能访问那个for循环中的代码。要在循环外访问它,必须在for循环外声明它。

另外要注意的一点是,当有多个相同名称的声明时,编译器将解析到最接近它的那个。例:

#include <iostream>
int main() {
    int a = 10;                         // Statement 1
    // We have only one declaration of a till now.
    std::cout << "Value of a before: " << a << std::endl;
    // This will declare a inside loop, hence it's visibility will
    // only be in the loop.
    for(int a = 1; a < 5; a++) {        // Statement 2
        /*
        When we refer a in the cout statement, it can refer to the
        one define outside the loop in Statement 1 or inside the 
        loop in Statement 2. The way compiler is designed it will
        always look for the closest declaration (Statement 2 in 
        this case) and work accordingly.
        */
        std::cout << "Value of a inside loop: " << a << std::endl;
    }
    std::cout << std::endl;

    for(int i = 0; i < 3; i++)          // Statement 3
        std::cout << "Value of i inside loop: " << i << std::endl;
    int i = 10;                         // Statement 4
    /*
    i has been declared in Statement 3 and Statement 4.
    However, the one declared in Statement 3 can only be accessed 
    within the for loop. Thus, the following statement will refer 
    to the declaration in Statement 4.
    */
    std::cout << "Value of i after loop: " << i << std::endl;
}

此外,在您的情况下,您可能希望与swap(A[min], A[i])中的A[i]交换。因此,代码应该如下:

void selectionsort(int size, int A[]) {
    for(int i = 0; i< size-1; i++) {
        int min = i;
        for(int j = i+1; j < size; j++) {
            if(A[min] > A[j])
                min = j;
        }
        swap(A[min], A[i]);
    }
}