+ 4

# What does this mean?Related to int

int &x What does &x mean

8th Apr 2017, 6:37 AM
Maulik Bharatsinh Parmar
+ 13
& is an operator that returns the memory address of where a variable is stored. So in this case, &x returns x's location in memory. But it's not meant to be used like this. Addresses are assigned to pointers. Something like this: int *ptr = &x; //*ptr points to x's address.
8th Apr 2017, 6:49 AM
Tamra
+ 13
When you pass a variable into a function and then change it, that change isn't reflected when the function ends. This is called passing by value, because you only send the value inside a variable, and not the variable itself. Ex: int x = 10; triple(x); //Sends what x is holding (10) cout << x; //Still 10 void triple(int x) { x *= 3} Using pointers, you can change a variable and keep that change. This is called passing by reference, because you let the function reference the variable itself, and not a copy of its value. Ex: int x = 10; triple(&x); //Sends the address of x cout << x; //Prints 30 void triple(int *x) { x *= 3 } //*x is a pointer to receive the address This is used so that a function can return multiple values at once.
8th Apr 2017, 7:05 AM
Tamra
+ 6
2 USES OF "&" IN C++ 1) To denote the "address-of" operator, which accesses the address in memory where a variable is stored. (Check out the lesson about POINTERS here at Sololearn) int x = 50; intÂ  *p; p = &x; cout << x << endl;Â Â Â  // Outputs 50 (value of "x") cout << p << endl;Â Â Â  // Outputs 0x29fee8 (x's memory location) cout << *p << endl;Â Â  // Outputs 50 (value of variable "x" stored in the pointer p) 2) To declare a REFERENCE variable. It is used to provide an alternative name or alias to an existing variable. int n = 5;Â Â Â Â Â Â  // Declares the variable "n" int &x = n;Â Â Â  // "x" is a reference to "n" x = 20Â Â Â Â  // Value of "n" is now changed to 20 cout << n << endl;Â Â Â Â  // Outputs 20 ------------------------------------------------------------ WHAT ARE POINTERS AND REFERENCES FOR? Both can be used to change local variables of one function inside another function. Both can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite these similarities, there are several differences. References for instance, are useful when the two variables are in different scopes (in different functions). They are designed to be used as parameters (arguments) to functions. Let's say references are a more elegant way of passing values to functions and returning values from functions (without a return statement). ------------------------------------------------------------ WHY SHOULD WE USE POINTERS AND REFERENCES? Basically for best performance. This way we can directly manipulate memory to efficiently manage it.
8th Apr 2017, 9:32 AM
Pao
+ 2
Can you give me a example on where it is helpful?
8th Apr 2017, 6:50 AM
Maulik Bharatsinh Parmar