0
What is the diference between this two codes?
#include <iostream> #include <string> using namespace std; int main() { string food = "Pizza"; string meal = food; cout << food << "\n"; cout << meal << "\n"; return 0; } AND: #include <iostream> #include <string> using namespace std; int main() { string food = "Pizza"; string &meal = food; cout << food << "\n"; cout << meal << "\n"; return 0; } Tem output is th same but I don't know is they work the same way. Thank you!
4 Answers
+ 5
To understand clearly,
Let's assign meal to something
For example,
meal ="fish";
With 1st method, output of food is still Pizza and output of meal is fish
With 2nd method, both output of food and meal are fish
Here you can read some explanation also.đ
https://www.sololearn.com/Discuss/710118/?ref=app
+ 2
In the second example meal is a reference. Basically it's just another name for a food variable.
So in the first example you create a new variable that equals the food variable, when in the second example you just use another name "meal" to reference to the food variable.
Here is more on references, if you are interested:
https://www.tutorialspoint.com/cplusplus/cpp_references.htm
+ 2
TheLaPpY14, Nope references still occupy memory.
The practical difference is that if you would change food in the first example, it would only change food variable. But if you change food in the second example, meal will now be a reference to the new value...
+ 1
So basically in the first code I have 2 variable spending different part of the memory. And in the second is the same memory but is like the meal is linked with the food?
So the difference is that the second is optimised since it only need one space in the memory while the first needs two?