Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

what does double& setValues( int i ) do? I would like to know about &setvalues,

ID: 3923821 • Letter: W

Question

what does double& setValues( int i ) do? I would like to know about &setvalues, where is it pointing or storing address of? Please explain thoroughly. Thanks.

#include

#include

using namespace std;

double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};

double& setValues( int i )

{

return vals[i]; // return a reference to the ith element

}

// main function to call above defined function.

int main ()

{

cout << "The address of vals: " << &vals << endl;

cout << "The address of setvalues: " << &setValues << endl;

cout << "Value before change" << endl;

for ( int i = 0; i < 5; i++ )

{

cout << "vals[" << i << "] = ";

cout << vals[i] << endl;

}

  

setValues(1) = 20.23; // change 2nd element

setValues(3) = 70.8; // change 4th element

  

cout << "Value after change" << endl;

for ( int i = 0; i < 5; i++ )

{

cout << "vals[" << i << "] = ";

cout << vals[i] << endl;

}

return 0;

}

My question is: what does double& setValues( int i ) do? I would like to know about &setvalues, where is it pointing or storing address of?

Explanation / Answer

#include <iostream>
//#include
using namespace std;
double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};
double& setValues( int i )
{
return vals[i]; // return a reference to the ith element
}

// main function to call above defined function.
int main ()
{
cout << "The address of vals: " << &vals << endl;
cout << "The address of setvalues: " << &setValues << endl;
cout << "Value before change" << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
  
setValues(1) = 20.23; // change 2nd element
setValues(3) = 70.8; // change 4th element
  
cout << "Value after change" << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
return 0;
}

Hi, setvalues method : return the reference of an element of vals array based on index passed to it

Ex:
   setvalues(3) : return the reference of 4th element of vals array, so if you change this referenced variable, it will
                   directly affect the value of vals (element stored at index 3)

   &setvalues : address of function setvalues