Results 1 to 15 of 15

Thread: Pass by Reference

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2001
    Posts
    485

    Pass by Reference [RESOLVED]

    Hi,

    I found this as a sample Function from an exercise.

    Code:
    int search(const tvector<Student>& list, const string& idnum);
    And I was wondering, is there any difference if the function was declared as
    Code:
    int search(const tvector<Student> &list, const string &idnum);
    What does the ampersand ( & ) means in the 1st code?

    Thanks.

    Harddisk
    Last edited by Harddisk; Oct 10th, 2005 at 10:13 PM.

  2. #2
    Hyperactive Member Amon Ra's Avatar
    Join Date
    Feb 2001
    Location
    In some cave on Uranus...
    Posts
    500

    Talking

    Maybe I am wrong, but they both mean the same thing...
    It does not matter where you put the ampersand...
    Amon Ra
    The Power of Learning.

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2001
    Posts
    485
    Ok, got it.

    And the & means to pass by reference right?

    Then why does it has to be "const <type> variable" ?

    I know that if const is applied, the value can't be changed, and what's the point of passing by reference anyway?

    Thanks

    Harddisk

  4. #4
    Aragorn
    Guest

    i'll try to help on that

    I'm not completely sure about what i'm gonna say, anyway...

    the & symbol means to take the address of..., so &i is the address of i. And that is what passing by reference means: you tell the function the address of the value that it has to use, therefore the function can go thaere and change the value such that when the function exits the value remains changed.

    If wou wouldn't pass by reference you would be creating a copy of the object being passed everytime you call the function, and this would be using the copy (not the original i value), so no changes would remain when the function returns.
    Now, when you have const &i, it means a constant pointer to (address of...) i, which doesn't mean a constant value of i.

    Hope i made sense... and were right!

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2001
    Posts
    485
    Now, when you have const &i, it means a constant pointer to (address of...) i, which doesn't mean a constant value of i.
    Now, that's coooooll

    So, in another word, I can change the value of &i and it wont cause any problem at all.

    Simply interesting.

    Thanks

    Harddisk

  6. #6
    Aragorn
    Guest
    remember &i is the address of i. I don't think you can go around doing things like this
    Code:
    &i = &some_other_var;
    Probably you can't even compile this.

    What you can do is (and that is what you mean i hope) accessing the contents of that address by removing the & symbol like
    Code:
    #include <iostream>
    #include <conio>
    
    void myFunc(int input, int &output) {
       output = 4*input;
       input = 0;  // Try to change the value: it will change within this
    }                   // function, but not after returning
    
    void main() {
       int i = 2;
       int o = 3;
       cout << "Before the call to myFunc: " << endl;
       cout << "i: " << i << endl;
       cout << "o: " << o << endl;
    
       myFunc(i, o);
    
       cout << "After the call to myFunc: " << endl;
       cout << "i: " << i << "  ... See it didn't change" << endl;
       cout << "o: " << o << "  ... and this DID change!" << endl;
       getch();
    }
    Well i hope that made it clearer.

  7. #7
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221

    Re: i'll try to help on that

    Originally posted by Aragorn

    Now, when you have const &i, it means a constant pointer to (address of...) i, which doesn't mean a constant value of i.

    Hope i made sense... and were right!
    Not exactly. I think you all get confused if you go on like this.

    First, dont' mix up pointers and references. They are used for the same purposes mostly, but there are fundamental differences.

    1. References are always constant, you can't change a reference to point to something else, also a reference allways points to something, whereas a pointer can point to 0. (which means it's a null pointer)

    2. References name access their contents, not their pointer value. ie i=5 changes the objects that i is pointing towards. Pointers need you to dereference to access their contents, using * dereferencing operator.

    Second a constant reference is pointing to a non-mutable object, that is the compiler has to watch out to not change the contents of the reference.

    Passing a constant reference is an agreement for the function that it won't change the object passed. This way you eliminate lots of debugging time if there's something wrong with the function. If the type of which object you passed constant has functions, they are able to change the value on the object, so therefore you can declare a function constant by putting const after the declaration of the functions parentesis. The function therefore can only call const functions on the constant reference.

    & operator is the addressof (refer) operator, you can use it to pass a object as a pointer, not reference, because & will return a pointer to the object you referer.
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  8. #8
    Let's say you have this

    Code:
    #include <iostream.h>
    
    void swap(int &a, int &b)
    {
        int cache;
        cache = a;
        a = b;
        b = cache;
    }
        
    
    int main()
    {
        int a = 1, b = 2;
        cout << a << " " << b << endl;
        return 0;
    }
    This (theoretically ) prints out "2 1". If you were to remove the ampersands, it would print out "1 2" because it would be modifiying a copy instead of the reference.

  9. #9
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    That was however not the issue
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  10. #10
    I was explaining what the ampersands did.

  11. #11
    Aragorn
    Guest
    thanks for clarifying, kedaman.

  12. #12
    Originally posted by Harddisk
    Ok, got it.

    And the & means to pass by reference right?

    Then why does it has to be "const <type> variable" ?

    I know that if const is applied, the value can't be changed, and what's the point of passing by reference anyway?

    Thanks

    Harddisk
    It saves memory.

  13. #13
    Aragorn
    Guest
    thanks for clarifying, kedaman.

  14. #14

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2001
    Posts
    485
    Thanks ya'll for helping me out
    So to speak:

    Then why does it has to be "const <type> variable" ?
    kedaman
    Second a constant reference is pointing to a non-mutable object, that is the compiler has to watch out to not change the contents of the reference.

    Passing a constant reference is an agreement for the function that it won't change the object passed. This way you eliminate lots of debugging time if there's something wrong with the function. If the type of which object you passed constant has functions, they are able to change the value on the object, so therefore you can declare a function constant by putting const after the declaration of the functions parentesis. The function therefore can only call const functions on the constant reference.
    Something which VB can't do. <grin>

    I know that if const is applied, the value can't be changed, and what's the point of passing by reference anyway?
    filburt1
    It saves memory.
    Ok, I sorta figured this out.
    Anyway, even if pass by value, the memory is restored after the function exited, right?

    Well, the 2nd question is sorta related to the 1st one. I guess kedaman got the answer to my main query.

    Does it serve any other purpose, except for easier debugging?

    Thanks

    Harddisk

    PS: I did a lot of ByVal in VB, hoping not to make any mistakes/changes onto the parameters' values <grin>
    Last edited by Harddisk; Aug 7th, 2001 at 01:38 PM.

  15. #15
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    Const can be omited any time, but it is not recommended. When you make a big program, you usually get stuck due to bugs that are hard to trace. You spend hours and find nothing. I use const whenever possible, that is whenever a variable doesn't need to be mutable, i make it const. That way the compiler will always find the error at compile time instead of it becoming a bug. Const can be used on variables, references, pointers, the pointer reference of a pointer and functions.
    Does it serve any other purpose, except for easier debugging?
    This is the only (and very good) use of Const.
    Anyway, even if pass by value, the memory is restored after the function exited, right?
    All variables, including the parameters are removed from the stack when the function exits. The stack pointer reverts to the point before the function was called.
    PS: I did a lot of ByVal in VB, hoping not to make any mistakes/changes onto the parameters' values <grin>
    Regularily, passing by value is slower than by reference especially if the object is big. The objects in vb are though pointers so it doesn't matter, however UDT's take up space.
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width