1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Function arguments, pass by pointer or reference?

Discussion in 'C' started by hseldon, Feb 20, 2011.

  1. hseldon

    hseldon New Member

    Joined:
    Dec 3, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    Which do you think is best? or cons/pros of each of passing by pointer vs passing by reference.
     
  2. lionaneesh

    lionaneesh Active Member

    Joined:
    Mar 21, 2010
    Messages:
    848
    Likes Received:
    224
    Trophy Points:
    43
    Occupation:
    Student
    Location:
    India
    Passing arguments by pointers allows the function to change our data in the pointed address..

    Passing by reference allows us to safeguard our data...

    Now lets test it :-

    function.c

    Code:
    #include<stdio.h>
    
    void passByPointer(int * input)
    {
    	*input = 100;
    }
    void passByReference(int input)
    {
    	input = 1337;
    }
    
    int main()
    {
    	int NumberToTest = 1337;
    	printf("Input = %d\n",NumberToTest);
    	passByPointer(&NumberToTest);		// change to 100
    	printf("Input = %d\n",NumberToTest); // should turn to 100
    	passByReference(NumberToTest);		
    	printf("Input = %d\n",NumberToTest); // Should be unchanged still will be 100
    	return(0);
    }
    

    Compiling


    Code:
    gcc function.c -o function
    
    Running :-

    Code:
    aneesh@aneesh-laptop:~/Programming/C$ ./function 
    Input = 1337
    Input = 100
    Input = 100
    
    Hope this helps...
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,287
    Likes Received:
    364
    Trophy Points:
    83
    You are getting confused with Pass By reference with Pass By Value.
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Neither is better; they are different tools for different jobs. You may as well ask which is better out of a hammer and a screwdriver.
     
  5. lionaneesh

    lionaneesh Active Member

    Joined:
    Mar 21, 2010
    Messages:
    848
    Likes Received:
    224
    Trophy Points:
    43
    Occupation:
    Student
    Location:
    India
    Yes...
    Sorry about that!!!
     
  6. UATLevan

    UATLevan New Member

    Joined:
    Mar 3, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    There really is no best, you have to know why you're passing by that choice when you create the function. One advantage of pass by pointer is you can set them to NULL to represent different things in your function while references have to point to an object even though that object might not be valid.


    Allen LeVan
    UAT Student
     

Share This Page