Thread: Pass by reference?

  1. #1
    Registered User
    Join Date
    Apr 2015
    Location
    Staten Island, New York, United States
    Posts
    22

    Pass by reference?

    I need help with an assignment guys. I'm not sure where to even start on this one.
    Write a program that will use a function called “swapFunction” which swaps two values. The functionshould have 2 parameters passed by reference. The function does not return anything. You need tooverload the function to work with integer, character, and double data types. You need to submit asource code that shows the function definition as well as main() ( show how the function is called withinteger values, character values, and double values).
    I don't recall learning this in class.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Compile and run this program:
    Code:
    #include <iostream>
    
    void setTo456(int& y)
    {
        y = 456;
    }
    
    int main()
    {
        int x = 123;
        std::cout << x << std::endl;
        setTo456(x);
        std::cout << x << std::endl;
    }
    The idea here is that the int& syntax in the parameter of the setTo456 function declares y to be a reference parameter, i.e., of type reference to int. This way, when setTo456(x) is called, y serves as an alias of x, so assigning 456 to y effectively assigns 456 to x.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Pass by reference in C++ probably means this:
    Code:
    void swap(int& a, int& b)
    A reference behaves just like a dereferenced pointer. When you pass it to a function, think of it as that you're passing the variable itself, not a copy of it.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 02-14-2012, 07:45 PM
  2. Pass by value/reference
    By Niels_M in forum C Programming
    Replies: 14
    Last Post: 11-07-2010, 01:35 PM
  3. Pass by reference vs pass by pointer
    By Non@pp in forum C++ Programming
    Replies: 10
    Last Post: 02-21-2006, 01:06 PM
  4. pass be reference versus pass by value
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 08-01-2002, 01:03 PM