Reputation: 6431
what's the difference between these signatures?
T * f(T & identifier);
T & f(T & identifier);
T f(T & identifier);
void f(T * identifier);
void f(T & identifier);
void f(T identifier);
I met pointers in c, but the amperstand in function signature is new for me. Can Anyone explain this?
Upvotes: 1
Views: 1026
Reputation: 106539
T * f(T & identifier);
This is a function which takes a reference to T and returns a pointer to T.
T & f(T & identifier);
This is a function which takes a reference to T and returns a reference to T.
T f(T & identifier);
This one takes a reference to a T and returns a copy of a T.
void f(T * identifier);
This one takes a pointer to a T and returns nothing.
void f(T & identifier);
This one takes a reference to a T and returns nothing.
void f(T identifier);
This one takes a T by value (copies) and returns nothing.
References behave almost exactly like pointers except a reference is never going to be set to NULL, and a reference is implicitly created and dereferenced for you so you don't need to deal with pointer syntax while calling the function or inside the function.
Upvotes: 1
Reputation: 46607
An ampersand in a type declaration indicates a reference type.
int i = 4;
int& refi = i; // reference to i
int* ptri = &i; // pointer to i
refi = 6; // modifies original 'i', no explicit dereferencing necessary
*ptri = 6; // modifies through the pointer
References have many similarities with pointers, but they're easier to use and less error-prone if address arithmetic is not needed. Also, unlike pointers, references can't be rebound to 'point' to another object after their initialization. Just ask google for references vs. pointers in C++.
Upvotes: 2