Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, what does & mean after a function's return type?

Tags:

c++

In a C++ function like this:

int& getNumber(); 

what does the & mean? Is it different from:

int getNumber(); 
like image 951
NellerLess Avatar asked Mar 04 '10 14:03

NellerLess


People also ask

What does \= mean in C?

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. *=

What does -= in C mean?

-= 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.


2 Answers

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; 
like image 109
sergiom Avatar answered Sep 29 '22 16:09

sergiom


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

like image 27
Nick Meyer Avatar answered Sep 29 '22 15:09

Nick Meyer