Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning reference of formal parameter

Tags:

c++

Please easy go on me if this is the very basic question.

returning reference from the function, i could see some benefits like. Here is the pseudo code.

int myarr[] = { .....  }

int & myfunction(int index)
{
  return myarr[index]
}

myfunction(1) = 20;  // sets the value to myarr[1].

I tried with the below code:

#include <iostream>
using namespace std;

int & topper (int & x, int & y)
{
  return (x>y)?x:y;
}

int main()
{
  int a=10, b=20;
  int c;
  c=topper(a,b);
  cout <<"Topper "<<c<<endl;
  c=100;
  cout <<" a value is "<<a<<endl;
  return 0;
}

Question:

My expectation is to print 100 for variable a. I am passing reference of a to topper() functions, and returns the same reference of a, and assign to c.

I'm sure some main point i am missing that when we declare int c, it should not be a different memory location, rather it should point to return the c value into different location but we have to make a reference.

like image 888
Whoami Avatar asked Feb 27 '26 16:02

Whoami


2 Answers

and returns the same reference of 'a', and assign to 'c'.

Yes, you're returning b (not a) by reference, but you're assigning it to c by value, so you could change code to:

int & c = topper(a, b);
cout << "Topper " << c << endl;
c = 100;
cout << " b value is "<< b << endl;
like image 151
songyuanyao Avatar answered Mar 01 '26 10:03

songyuanyao


Lot of confusion in your question.

But if you are trying to alias the variable c to point to topper between a and b, try something like:

int& c = topper(a,b);

now c is a reference to whatever the topper returns and by changing c, you change the variable returned by topper.

like image 27
karthiksatyanarayana Avatar answered Mar 01 '26 10:03

karthiksatyanarayana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!