-
return reference
I know how item_array[2] becomes 0 but i don't know why. since array[] is not a reference to item_array[2] how does the function biggest, which returns a reference to array[bigges], assign 0 to item_array[2]???
could someone please explain this to me, thank you.
Code:
#include <iostream>
int& biggest(int array[], int n_elements){
int index;
int biggest;
biggest = 0;
for(index = 1; index < n_elements; ++index){
if(array[biggest] < array[index])
biggest = index;
}
return(array[biggest]);
}
int main(){
using namespace std;
int item_array[5] = {1, 2, 5000, 3, 4};
cout << "The biggest element is " << biggest(item_array, 5) << endl;
biggest(item_array, 5) = 0;
cout << item_array[2] << endl;
return 0;
}
-
when it is returning it is returning a value..array[biggest] is the same thing as a variable name...so it is returning array[2] which contains 5000...it returns a reference to it..so when you do
Code:
biggest(item_array, 5) = 0;
it sets array[2] = 0;
remember the reason this work with your arrays because arrays are very similar to pointers....when you pass an array to a function you are actually passing the address of the array pointing to the first element so you could have done pointer notation like '*(array + 2) == array[2]'....if you do this with normal variables you are just returning a local variable which is a no-no!..