In the following code (for bubble sort), the variable origN was not referenced at all after its declaration, but at the end of the program, the value of origN is output as 1 (instead of 4):
int main(){
int arr[] = {3,4,2,1};
int origN = 4;
int n = 4;
while(true)
{
bool swapped = false;
for(int i = 0; i<n; ++i)
{
if(arr[i] < arr[i-1])
{
swap(arr[i],arr[i-1]);
swapped = true;
}
}
n -= 1;
if(!swapped)
break;
}
cout<<"origN="<<origN<<endl;
return 0;
}
But if I use the variable n as a pointer:
int *n = new int(4);
the value of origN remains unchanged, and is correctly output as 4!
Why is the value of origN changing along with the value of n?