SWAP error

Ok, this error comes and goes with using the swap command. I've tried changing the i to something else in case it was due to some sort of internal name collision, no luck. The compiler error says what the remedy is, but really? The fact that it comes and goes makes me think there could be a different problem.

error: LINE 17

g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\main.o" "..\\src\\main.cpp" 
..\src\main.cpp: In function 'int main()':
..\src\main.cpp:17:16: error: name lookup of 'i' changed for ISO 'for' scoping [-fpermissive]
     swap(array[i],array[j]);
                ^
..\src\main.cpp:17:16: note: (if you use '-fpermissive' G++ will accept your code)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int main ()
{
    int array []= {4,2,3,10,5};
    int array_size = sizeof(array) /sizeof(array[0]);

    for(int j(0); j<array_size; ++j)
		{

    int smallest = array[j] ; int smallest_index = 0;
    for ( int i=j;  i < array_size;  ++i )
    if ( array[i] < smallest )
             {smallest = array[i] ;
              smallest_index = i; }
   --> swap(array[i],array[j]);
    cout << "Smallest number:"<<smallest<<"  "<<"Smallest number index:"<<smallest_index;
    cout<<" Index begin :"<<j<<endl;
    for (int k(j); k<array_size; ++k)
    	{cout<<array[k]<<" ";}
    	cout<<endl;


		}
    return 0;
}
Last edited on
Well since your call to swap is outside the for loop that declares i, the i in that call is not existent, it went out of scope after the if() statement of the loop, because you didn't use any braces. If you want to use this variable after the loop you should declare it before the loop. If you want that swap() call to be controlled by the for() loop, you need to use braces.

1
2
3
4
...
   int i;
   for(i = 0; i < array_size; ++i) 
...
Thank you!
Topic archived. No new replies allowed.