More Group Sites
School Rankings
Jobless Net
Better Home
Enviro++


Help | Subscribe/Unsubscribe | Rules | Other Group Sites: Better Education | Better Education Forum
Welcome Guest Search | Active Topics | Members | Log In | Register

An example of passing by value and reference Options · View
hong
Posted: Saturday, October 24, 2009 4:53:26 AM

Rank: Administration
Groups: Administration

Joined: 11/23/2008
Posts: 335
Points: 711
Location: Australia
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.

Code:
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;
}


Code:
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;
}


Code:

    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.

Sponsor
Posted: Saturday, October 24, 2009 4:53:26 AM
Users browsing this topic
Guest


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.

Main Forum RSS : RSS

ASPNET Theme created by Boskone (Dan Ferguson)
Powered by Yet Another Forum.net version 1.9.1.8 (NET v2.0) - 3/29/2008
Copyright © 2003-2008 Yet Another Forum.net. All rights reserved.
This page was generated in 0.249 seconds.