为什么我在代码块中遇到编译错误,因为我使用的变量超出了范围?
why i'am getting compilation error in code blocks that i'm using variables out of scope?
错误信息代码块
当选择排序时,在调用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]);
}
}
相关文章:
- 在 c++ 中确定堆栈上的变量范围
- C++中静态方法的局部变量范围
- 功能原型变量范围C
- C 公共变量范围混乱
- 指向本地变量的指针存储在此变量范围之外
- C 变量范围
- 在函数的参数列表中初始初始化的变量范围
- 由于变量范围导致的段故障
- 友元运算符中的变量范围
- CMake <PROJECT-NAME>_SOURCE_DIR 变量范围
- switch 语句中的奇数变量范围
- C++ try 中的变量范围
- C++ 引用变量范围问题
- 更改静态变量范围
- C++向量、常量字符*、变量范围和生存期
- 对变量范围感到困惑 - 析构函数意外调用
- 限制变量范围的利弊
- 我的C++变量(范围相关)有什么问题?
- c++中变量范围嵌套不当
- Qt5、lambda和变量范围