Thread: return reference

  1. #1
    Registered User
    Join Date
    Mar 2003

    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.

    #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;
    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;

  2. #2
    samurai warrior nextus's Avatar
    Join Date
    Nov 2001
    when it is returning it is returning a value..array[biggest] is the same thing as a variable it is returning array[2] which contains returns a reference to when you do

    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!..
    nextus, the samurai warrior

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  2. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  3. C OpenGL Compiler Error?
    By Matt3000 in forum C Programming
    Replies: 12
    Last Post: 07-07-2006, 04:42 PM
  4. Alegro closes out on me
    By campsoup1988 in forum C++ Programming
    Replies: 8
    Last Post: 04-03-2006, 10:40 AM
  5. string class errors
    By CodeMonkey in forum C++ Programming
    Replies: 13
    Last Post: 07-20-2003, 11:20 PM