Home c++ Ampersand in function parameters

Ampersand in function parameters




Hello, can you please tell me how it works? Let’s say you have a function like this:

void foo (int & amp; one, int two) {
  one = two;
int s1 = 1;
int s2 = 2;
foo (s1, s2);

How does the ampersand before the function parameter one work? I understand that the function works on a variable that is allocated in static memory. It turns out that we pass a value of type int to the function, then we take its address. But why in the body of a function can we work with it as with an ordinary variable, and not as with a pointer? In theory, it would be necessary to dereference.

This construction is understandable:

void foo (int * one, int two)
  * one = two;

and when calling the function we pass the parameters (& amp; s1, s2); .

Answer 1, authority 100%

Therefore, we write & amp; so that we can write one = two , not * one = two . Here the whole point is that the pointer is explicitly passed when they want to work directly with it, when you need to know its value. When we want to work with the value of a variable, but not only in the function in which it is created, but also in the “hereditary” ones, we pass it by reference.

You can of course say something like “I’m not used to this, I’d rather pass addresses explicitly”, but believe me, passing a variable by reference in case you need to work with the variable itself is the right approach to programming. A good programmer must be able to write GOOD code – not only algorithmically efficient, but also as understandable as possible; such that its essence could be understood by another programmer, even who saw it for the first time.

In C #, passing a variable by reference looks more beautiful, it is simple there both in the caller and in the called methods, before the variable, the word ref (or out , which goes there meaning “additional return value”).

Answer 2, authority 40%

read the code below, I think you’ll figure it out

# include & lt; iostream & gt;
using namespace std;
int main () {
  int value = 0; // variable initialized to zero
  cout & lt; & lt; value & lt; & lt; endl; // will print zero
  int & amp; link = value; // variable reference (cannot exist without specifying the variable name)
  link = 100; // through the link we write the value 100 to the variable
  cout & lt; & lt; value & lt; & lt; endl; // will print 100
  return 0;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions