Why do I need an ampersand in a function parameter?
Please tell me what role the ampersand plays in the parameter of this function because the program works correctly both with and without it
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> T_summands;
void print_summands(int n_start,const T_summands& summands)
{
cout << n_start << "=";
for(T_summands::const_iterator summands_it = summands.begin(); summands_it != summands.end(); ++summands_it)
{
cout << *summands_it << (summands_it != summands.end() - 1 ? " + " : "\n");
}
}
0
1 answers
For understanding - well, consider that when passing by reference, you're just passing a pointer, but you don't have to dereference it all the time.
Type
void f(int * x) { *x = *x * 2; }
...
int y = 4;
f(&y);
The same via the link -
void f(int& x) { x = x * 2; }
...
int y = 4;
f(y);
This is, of course, an approximation, but it is suitable for understanding.
When you pass without reference, by value - a copy is created. Something like this:
void f(int x) { x = x * 2; }
It's as if (inaccurate! just for understanding!!)
void f(int * y)
{
int x;
x = *y;
x = x * 2;
}
At the "household" level-the value passed by is not changes what is passed by reference-changes the passed variable itself.
void f(int& x) { x = x * 2; }
...
int y = 4;
f(y); // Теперь y == 8
void f(int x) { x = x * 2; }
...
int y = 4;
f(y); // y == 4...
3
Author: Harry, 2020-02-27 15:04:59