Thread: Why return values from a function by ref, address

  1. #1
    Registered User
    Join Date
    Nov 2013
    Posts
    107

    Why return values from a function by ref, address

    You can return values from functions by ref, address or value you can also do this with parameters, so what is the difference, if you have full return of a passed parameter by ref or address why would you need to ever return the function as a whole?

    For ex

    Code:
    int nValue(int& y){
    y++;
    }
    
    or int& nVlaue(int y){
    return y;
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Your two examples are both flawed. The fact a compiler allows you to do something doesn't mean you should do it (although most compilers, if configured to picky warning levels, will issue warnings about the problems).

    The first version falls off the end of the function, so the caller will exhibit undefined behaviour if it tries to use the return value.

    The second function returns a reference to an argument passed by value. Since an argument passed by value ceases to exist when the function return, the caller will also exhibit undefined behaviour when it attempts to use the returned reference.

    An example that would demonstrate the usage of references would be
    Code:
    int &biggest(int &x, int &y)
    {
         return (x >= y ? x  : y);    //   this selects the biggest of x and y, and returns a reference to it
    }
    
    int main()
    {
         int a = 5, b = 7;
         biggest(a,b) = 32;     //   b is larger, so this sets b to be 32.
    
         int p = 16, q = 2;
         biggest(p, q) = 32;    //   p is larger, so this statement sets p to 32
         return 0;
    }
    Pointers can be used in similar ways, albeit the syntax is different. There are also the same caveats - a function should not return the address of a local variable, nor should it return a pointer to a argument passed by value.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 06-10-2013, 04:03 PM
  2. I need to see a function return address.
    By esbo in forum C Programming
    Replies: 55
    Last Post: 01-17-2013, 03:59 PM
  3. function calls and return address
    By acpower in forum C Programming
    Replies: 2
    Last Post: 06-05-2012, 05:58 AM
  4. modifying a return address of a function
    By jay1313 in forum C Programming
    Replies: 3
    Last Post: 09-18-2008, 09:09 AM
  5. Replies: 2
    Last Post: 12-07-2004, 02:31 AM