Note: Containing loop

This code compiles and runs, outputs what I want, but still produces an error. From what I understand this is undefined behavior, but to me this all seems pretty novel, all pretty understandable. What doesn't my compiler understand about it?

errors:
14:9, note: contains loop.
warning: iteration 9u invokes undefined behavior

I also did figure out how to make the errors go away, in that I changed the maximum i iteration to be 8, or less than 9, but why is it considered a bad practice to rerun the loop in case you didn't end up sorting it properly, say I had user input?

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()
{
    //to bubble sort, run through an array, record a value, if it's lower than the next, keep it, if higher than the next, swap it.  
    //redo this length times.  
    int intArray[10] = {10,9,8,7,6,5,4,3,2,1};
    int temp;
    for(int j = 0; j < 10; j++)
    {
        for(int i = 0; i < 10; i++)
        {
            if(intArray[i] > intArray[i+1]) 
            { 
                temp = intArray[i];
                intArray[i] = intArray[i+1];
                intArray[i+1] = temp;
            } 
        }
    }
    for(int i = 0; i < 10; i++)
    {
        cout << "Int array " << i << ":  " << intArray[i] << endl;
    }
}
Last edited on
Your accessing your array out of bounds on lines 15, 18, and 19 on the last iteration of the loop because of the addition.
You have declared intArray[] to have size 10. Indices count from 0 (in c++) so its elements are
intArray[0]
intArray[1]
.
.
intArray[9]

In your inner loop i <10, so the largest value is i=9.
On line 15 you then compare intArray[9] with ... intArray[10].
But intArray[10] doesn't exist.

So, your compiler is actually being quite kind to you, don't you think?
Would my code run and sort fine if I set the iterations down by 1? That's what I have it at now.
Yes

Actually, you can do better. Each pass puts another "sorted" one at the end, so:
(1) Once you've put the largest 9 in place, the final one is automatically in place. So you need 9 (or, in general, size-1) passes in j. Thus j=0 and j<9 would be Ok here.
(2) Each pass doesn't have to be as long, since each pass puts another one in a sorted position at the end. Hence, the i loop doesn't need to be as long; the loop condition could be i<9-j.

And it would be better if you didn't use the "magic number" 10.
Set
const int size = 10;
at the start and then (after making the changes above) replace every 10 by size, and every 9 by size-1.
Last edited on
Topic archived. No new replies allowed.