+ 2

Explain this code

#include <iostream> using namespace std; int x=15; int & f() { return x; } int main () { f()=10; cout<<x; }

23rd Nov 2018, 8:51 AM
AKEEL
AKEEL - avatar
3 Answers
+ 6
x is defined globally (declared outside main function) f returns a reference of x, so one can change the value by assigning the reference (alias) a different value, here 10 You can think of this as a shortcut of these steps: int& a = f(); a = 10; // after that, both a and x are 10, since both describe the same spot in memory (reference)
23rd Nov 2018, 9:43 AM
Matthias
Matthias - avatar
0
Thank you Matthias
25th Nov 2018, 3:51 AM
AKEEL
AKEEL - avatar
0
Thx Matthias & Akeel Mohamed 😃
25th Nov 2018, 3:53 AM
Ar NivethanđŸ€˜
Ar NivethanđŸ€˜ - avatar