More Group Sites
Education Books
School Rankings
Jobless Net
Better Home
Welcome Guest! To enable all features please Login or Register.



Go to last post Go to first unread
#1 Posted : Saturday, 24 October 2009 12:53:26 AM(UTC)

Rank: Administration


Groups: AcademicCoachingSchool, admin, Administration, BookSeller, CatholicSchool, CoachingAdult, CoachingProfessional, CoachingSports, ExtraCurriculumCoaching, IndependentSchool, Moderator, MusicTeacher, PrivateSchool, PublicSchool, SelectiveSchool, tutor
Joined: 23/11/2008(UTC)
Posts: 523

An example of passing by value and reference

In the following example, we examine passing by value via a pointer, passing by reference including a pointer to a pointer and const reference.

int f(int* pi, int **ppi, int& ri, const int& cri)
    int i1 = *pi + 1;
    //original poinetr modified in the function, but the integer pointed to will not change on return 
    pi = &i1;
    //the integer pointed to will change on return
    //*pi = i1;

    int i2 = **ppi + 1;
    int* pi2 = &i2;
    //ppi = &pi2;
    //instead do this to modify the pointer
    *ppi = pi2 + 1;

    int i3 = ri + 1;
    ri = i3;

    int i4 = cri + 1;
    //cannot compile because you cannot change const by reference
    //cri = i4;

    return i1 + i2 + i3 + i4;

int main()
    int i1 = 1;
    int i2 = 2;
    int i3 = 3;
    int i4 = 4;

    int* pi2 = &i2;
    int n = f(&i1, &pi2, i3, i4);
    return 0;


	i1	i2	i3	i4
start	1	2	3	4
return	1	x	4	4

As we discussed here, when a pointer is passed to a function, it is passed by value. So i1 is passed by value not reference. Even though the function f modified the local pointer, the original pointer is not affected. i2 is passed via a pointer to a pointer (ie. by reference), the original pointer is modified in the function call. Unlike i1 which is passed by a pointer, i3 is passed by reference and the original value is changed in the function call. i4 is passed by const reference so we cannot change the original value.

Edited by user Monday, 26 October 2009 4:52:11 AM(UTC)  | Reason: Not specified

Rss Feed  Atom Feed
Users browsing this topic
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.