1

I know following about reference

eg. int &ref=x; then ref and x are the names of same locations in memory. Memory is not allocated for reference unlike pointers.

I was writting a simple swap program in C++ using references which I successfully wrote.

Then i decided to try out what happens when a function which returns reference is LHS of an expression and now I am unable to predict the output of the below code.

#include<iostream.h>

int &  swap(int &,int &);   //function returns reference
void main()
{
    int x=10,y=20;
    int &ref1=x,&ref2=y;
    swap(ref1,ref2)=x;         //what happens here?
    cout<<x<<y;
}

int & swap(int &ref1,int &ref2)
{
    int temp;         
    temp=ref1;        //swap   
    ref1=ref2;        //code
    ref2=temp;        //here

    return ref2;      //tried out this(has nothing to do with swapping)
}

O/P 20 20

robbannn
  • 5,001
  • 1
  • 32
  • 47
user3126632
  • 467
  • 2
  • 8
  • 15
  • Educate people that write such code not to do it. If they insist on not changing, find a way to stop working with them. If you are one of those people, please change how you write code. – R Sahu Sep 22 '14 at 19:01
  • Memory may be allocated for references. – Neil Kirk Sep 22 '14 at 19:16

1 Answers1

1

There are two possible outcomes:

  1. "2010"
  2. "2020"

It depends on whether x on the right side is read before or after calling swap on the left.

The standard does not proscribe which happens, only that they are not interleaved.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • yes, looks like it. Just keep in mind that it could change without apparent cause. – Deduplicator Sep 22 '14 at 18:23
  • I've experimented a bit: `x` always gets evaluated first, however the result depends on the kind of `operator=` is defined. if `operator=(int&)` is used then the result is "20 20" (i.e. the reference of `x` is used). If `operator=(int)` is used then the value of `x` is copied before swap() and the result is "20 10". – mariusm Sep 22 '14 at 20:11