Question

C++ What does it mean when you pass by reference a function? Example: int & modify(){}...

C++ What does it mean when you pass by reference a function? Example:

int & modify(){}

same question with pointers. Example:

int * modify(){}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Alias:

Alias means another name of an existing variable. In C++, the reference variable is an alias.

For example:

int x;

int &y = x;

In the above statement, 'y' is an alias of variable 'x'.

Pass By Reference

When we pass the parameter as a reference, then the reference of the parameter is passed to the called function. The reference variable uses the pointer for implementation. A reference is the same object but a different name and it can't be assigned null. A reference variable can be used directly and there is no need for dereferencing operator '*'.

For example:

//method to return the reference of a variable
int & modify()
{   
return a;
}

In the above method, we return the reference of a variable.

When we want to make changes in the actual parameter then we should use the reference variable.

By using pointer:

int * modify()

{

}

In the above example, the address is return and we need the dereferenced operator to get the value.

Difference between pointer and reference:

  • A pointer hold the address of a variable but a reference is an alias name of a variable.
  • There is no need of a dereferenced operator for a reference variable.
  • On a pointer, we can use an increment operator but on the reference variable, we can't use it.
Add a comment
Know the answer?
Add Answer to:
C++ What does it mean when you pass by reference a function? Example: int & modify(){}...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT