Welcome to pickSourcecode.com Login | Register    
pickZy.com
 Home  | search  | games  | General  | C  | C++  | Java  | Php  | Networking  | Visual Basic  | VC++  | Win32  | MFC  | JavaScript  | Jobs  | JavaScript  | Post jobs
C - Pass-by-reference parameters       Share
2007-08-31 |  RatheeshTR  | Viewed: 300  |    1

Pass-by-reference parameters:

        Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. C onlyIn C, the corresponding parameter in the called function must be declared as a pointer type. C++ only In C++, the corresponding parameter can be declared as any reference type, not just a pointer type.


The following function swap uses reference parameters:

            void swap(int& a,int& b)
            {
                int temp = a;
                a = b;
                b = emp;
            }


Now, swap does have an effect on the arguments in the caller - as it must to be of any use. Thus:

              float x=10, y=20, z=0;
             swap(x, y);
             cout<< x<<", "<< y<< endl;


will result in 20, 10

Notice that the caller need not make any special indication of the reference nature of the arguments - that is all handled by the definition of the function: int& a,int& b.

Thus, void swap(int& a,int& b)
Just to drive the point home, let us examine a naive swap which uses pass-by-value.


        void swapSilly(int a,int b) //naive -- pass by value
             {
                  int temp=a;
                  a=b;
                  b=temp;
        }

Now, swap Silly does NOT have an effect on the arguments in the caller, hence the function has no effect. Thus:

          float x=10, y=20, z=0;
               swapSilly(x, y);
               printf ("%d , %d \n",x,y);

will result in 10, 20

Example program:

1. Swap two numbers


Latest topics
C - Arrays of structures  Viewed: 285
C - structures and functions  Viewed: 292
tcpdump by host name or ip  Viewed: 292
C - For loop statements  Viewed: 295
C - pointers and Arrays  Viewed: 295
C - File Access  Viewed: 295
C - pointers to pointers  Viewed: 296
C - Register variables  Viewed: 297
C - Static variables  Viewed: 299
C - Pass-by-reference parameters  Viewed: 300

Comments:





Submit comment's

Type:

User Comment's:

Submitted By:
Prof: Software Engineer
Tech: C ,Cpp
Send Mail: ratheesh



Related topics
C - Functions and program structure, Programmed pass-by-reference via pointers, Pass-by-reference parameters
C - Pass-by-reference parameters
C - pass-by-reference via pointers

Related References
c - swap num, pass-by-reference parameters
c - pass-by-reference via pointers

Web site contents © Copyright 2007, All rights reserved.
Help | Terms and Conditions | Privacy Policy | About Us