Thread: Easy question re: Calling by Value vs Reference

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    8

    Cool Easy question re: Calling by Value vs Reference

    Hi All, thanks in advance for any help....

    I'm having a hard time seeing the difference between calling by value vs calling by reference. In the following example, I receive the same result when the program is executed.

    I'm wondering if anyone can provide an example where using the call by reference would produce a different result, or at least some type of explanation on the difference?

    Here's the example:
    ________________

    int tripCBV(int);
    int tripCBR(int &);

    int main()
    {
    int number, result1, result2;

    cout << "enter a number to be tripled: ";
    cin >> number;

    result1 = tripCBV(number);
    result2 = tripCBR(number);

    cout << "CBV result is " << result1 << endl;
    cout << "CBV result is " << result2 << endl;

    return 0;
    }

    int tripCBV(int x)
    {
    int y;

    y = 3 * x;
    return y;
    }

    int tripCBR(int &x)
    {
    int y;

    y = 3 * x;
    return y;
    }

  2. #2
    Banned
    Join Date
    Jan 2003
    Posts
    1,708
    When you pass a variable by value to a function a copy of that variable is made. You can do anything you want to that copy of the value, and it will not change the value of the original variable. When you pass by reference a copy of the variable is not made, instead whenever you change the value of the reference the value of the original variable is also changed.

  3. #3
    Registered User
    Join Date
    Mar 2003
    Posts
    8
    Got it... thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C OpenGL Compiler Error?
    By Matt3000 in forum C Programming
    Replies: 12
    Last Post: 07-07-2006, 04:42 PM
  2. Another Embarassingly Easy Question
    By almo89 in forum C Programming
    Replies: 2
    Last Post: 02-11-2006, 04:59 PM
  3. Textbox
    By maxorator in forum Windows Programming
    Replies: 20
    Last Post: 09-25-2005, 10:04 AM
  4. Easy question, (should be) easy answer... ;-)
    By Unregistered in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 06-12-2002, 09:36 PM
  5. Dll question again. Reference to No-One
    By G'n'R in forum C Programming
    Replies: 0
    Last Post: 10-24-2001, 03:52 AM