In a C++ function like this:
int& getNumber();
what does the &
mean? Is it different from:
int getNumber();
It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A. *=
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C - A.
It's different.
int g_test = 0; int& getNumberReference() { return g_test; } int getNumberValue() { return g_test; } int main() { int& n = getNumberReference(); int m = getNumberValue(); n = 10; cout << g_test << endl; // prints 10 g_test = 0; m = 10; cout << g_test << endl; // prints 0 return 0; }
the getNumberReference() returns a reference, under the hood it's like a pointer that points to an integer variable. Any change applyed to the reference applies to the returned variable.
The getNumberReference() is also a left-value, therefore it can be used like this:
getNumberReference() = 10;
Yes, the int&
version returns a reference to an int
. The int
version returns an int
by value.
See the section on references in the C++ FAQ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With