I\'m currently reading through Accelerated C++ and I realized I don\'t really understand how & works in function signatures.
int* ptr=#
In the case of assigning variables (ie, int* ptr = &value
), using the ampersand will return the address of your variable (in this case, address of value
).
In function parameters, using the ampersand means you're passing access, or reference, to the same physical area in memory of the variable (if you don't use it, a copy is sent instead). If you use an asterisk as part of the parameter, you're specifying that you're passing a variable pointer, which will achieve almost the same thing. The difference here is that with an ampersand you'll have direct access to the variable via the name, but if you pass a pointer, you'll have to deference that pointer to get and manipulate the actual value:
void increase1(int &value) {
value++;
}
void increase2(int *value) {
(*value)++;
}
void increase3(int value) {
value++;
}
Note that increase3
does nothing to the original value you pass it because only a copy is sent:
int main() {
int number = 5;
increase1(number);
increase2(&number);
increase3(number);
return 0;
}
The value of number
at the end of the 3 function calls is 7, not 8.
You're inexplicitly copy-constructing copy
from str
. Yes, str
is a reference, but that doesn't mean you can't construct another object from it. In c++, the &
operator means one of 3 things -
&
is the bitwise AND.Another way to think about a reference (albeit slightly incorrect) is syntactic sugar for a dereferenced pointer.
int* ptr=#
1st case: Since ptr is a memory and it stores the address of a variable. The & operator returns the address of num in memory.
void DoSomething(string& str)
2nd case: The ampersand operator is used to show that the variable is being passed by reference and can be changed by the function.
So Basically the & operator has 2 functions depending on the context.