Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I was looking at simple c++ code and I saw something like int& b in a function.
I don't get it that what this & does here.
Any help would be appreciated.

What I have tried:

#include<iostream>

using namespace std;


int fun1(int a ,int& b);

int main(){
	int a=3,b=12;
	
	fun1(a,b);
	

}

int fun1(int a, int& b){
	a = a*b;
	b=a+7;
}
Posted
Updated 13-Jun-18 22:11pm
Comments
nv3 14-Jun-18 2:42am    
Any textbook on C++ would have told you :-) But solution 1 will get you there also.

In the function int fun1(int a ,int& b), a is an argument passed by value and b is an argument passed by reference.

The difference is explained here:
7.2 - Passing arguments by value | Learn C++[^]
7.3 - Passing arguments by reference | Learn C++[^]
 
Share this answer
 
v2
References are a way to implement function's out-parameters, like pointers did in plain C programming. C++17 offers destructuring in order to avoid them. Try for instance
#include <iostream>
#include <tuple>
#include <cmath>
using namespace std;

// rho and phi modification are visible to the caller
void polar( double x, double y, double & rho, double & phi)
{
  rho = sqrt(x*x + y*y);
  phi = atan2(x,y);
}

// prho, pphi provide access to actual caller variables
void c_style_polar( double x, double y, double * prho, double *pphi)
{
  *prho = sqrt(x*x +y*y);
  *pphi = atan2(x,y);
}

// the return value is an aggregate, the C++17 syntax allows to destructure it in plain doubles
tuple <double , double> tupled_polar(double x, double y)
{
  return make_tuple<double, double> ( sqrt(x*x+y*y), atan2(x,y));
}



int main()
{
  double x = 100, y = 100;

  // C++ out parameters
  {
    double rho, phi;
    rho = 0.0; phi = 0.0;
    polar(x, y, rho, phi);
    cout << "rho = " << rho << ", phi = " << phi << '\n';
  }

  // C-style out parameters
  {
    double rho,  phi;
    c_style_polar(x, y, &rho, &phi);
    cout << "rho = " << rho << ", phi = " << phi << '\n';
  }

  // C++17 destructuring
  {
    auto  [rho, phi] = tupled_polar(x, y);
    cout << "rho = " << rho << ", phi = " << phi << '\n';
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900