Bazaar output

Until this program, I've always believed that C++ always reads from top to bottom. I created this program, and it seems that later code can influence how earlier code works without having any correlation. I would greatly appreciate solution, but also a description as to why the code behaves this way.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{

    srand(time(0));     // using a time variable to generate a random number
    int arr[10];

    for(int i = 0; i < 10; i++){
        arr[i] = (rand()%100);  // rand() does not generate a new set of numbers that is different every time so srand(time(0)) is used as well
    }

    // printing unordered array
    cout << "Array (unsorted): ";
    for(int i = 0; i < 10; i++){
        cout << arr[i] << " ";
    }
    cout << endl;

    // bubble sort in ascending order
    int swaphold = -1, runner = 10, length = 10;
    for (int counter = length; counter > 0; counter --)
    {

        for(int i = 0; i < runner; i++)
        {
            if(arr[i] > arr[i + 1])
            {
                swaphold = arr[i + 1];
                arr[i + 1] = arr[i];
                arr[i] = swaphold;
            }
        }

        for(int i = 0; i < 10; i++)
        {
            cout << arr [i] << " ";
        }
        cout << endl;

        runner --;
    }
// if you un-comment the next line, you get an incorrect output. How can this be? All I am doing is declaring a variable after rest of the code. It should be independent, yes?
//int t = 9;

    return 0;
}.
Last edited on
The sort is accessing an out-of-range element arr[i + 1] when i == 9, that accesses element 10, which is outside the array.
Yes, I have solved the problem. But still, why does declaring an int after the other code change the output?
why does declaring an int after the other code change the output?

It just changes some area of memory which happens to correspond with the invalid access made in the sort.

But don't try to derive any rules from this. Simply, it is unpredictable behaviour, anything can happen, such as the program crashing, or worse, it not crashing and continuing as though nothing was wrong, but giving strange results or behaviour somewhere else.
Last edited on
Okay, I think I see. Thanks for the help.
Topic archived. No new replies allowed.