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.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace 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;
}.
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.