Code About Us Tutorial


  Pointers and References
    What are Pointers?
    Declaring Pointers
    The Indirection and Dereference operator
    What is a Reference?
    Using References
    Using Pointers and References
    The new Keyword
    The delete Keyword
    Passing By Reference
    Passing by Value


   
 

Home > Pointers and References > Passing by Value

November 29, 2009 4:21 am

   

Passing by Value

Now that we got passing by reference down, we can move onto passing by value. Remember what I said about passing by value, the address isn’t passed to the function, it makes a whole copy of the variable, but the original value isn’t modified. Notice how the swap function deals with the two values after it’s out of the function. Here is the same code but modified to pass by value, not reference.

 

 
//value.cpp

#include <iostream.h> #include "value.h"

//prototypes

void swap(int,int);

void main() { int num1, num2;

cout <<"Enter 2 numbers you wish to swap: " << endl; do { cin >> num1 >> num2; swap(num1,num2); cout <<"After Swap. Value of num1: " << num1 << "n"; cout <<"After Swap. Value of num2: " << num2 << endl; }while ((num1 != 0) && (num2 != 0)); //if you enter 0 for one of values, it will exit loop }

The changes I made are highlighted in bold. I took out the (&) operator because you don’t want the parameters to get the address of the two variables being passed, you want to just make an extra copy of the two variables being past.

 

 
//value.h
//This function uses passing by value

void swap(int y, int x) { cout <<"Before Swap, in function. Value of num1: " << y << "n"; cout <<"Before Swap, in function. Value of num2: " << x << "n";

int temp; temp = y; y = x; x = temp;

cout <<"After Swap, in function. Value of num1: " << y << "n"; cout <<"After Swap, in function. Value of num2: " << x << endl; }

Once you compile this code the output is this:

{FIG}

What was the major difference here? Well as you can see, The Swap function worked fine when it was in the function, it switched the two numbers like it was suppose to do. Look at the last two output lines. The numbers are back to normal! That’s because when the two variables passed, it didn’t take the addresses, it just made copies of the variables, so when you are out of the function the two variables you entered didn’t get modified.

Well I think that sums references and pointers well enough for you to know when you need to use them. Experiment a little; see what you can come up with using references and pointers. Please Rate this Code:


    Comments for: Passing by Value
  There are NO user contributed comments for Passing by Value.



Add Comment:
Name:
Email:


 «