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!

4th Oct 2021, 12:55 PM
TheLaPpY14
TheLaPpY14 - avatar
4 odpowiedzi
+ 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
4th Oct 2021, 1:30 PM
Myo Thuzar
Myo Thuzar - avatar
+ 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
4th Oct 2021, 1:21 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 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...
4th Oct 2021, 1:58 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 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?
4th Oct 2021, 1:54 PM
TheLaPpY14
TheLaPpY14 - avatar