Can someone please explain why we get the output we see in the following source code?
#include <iostream>
int main() {
int x{ 10 };
int &rx{ x };
rx = 123;
std::cout << x << " " << rx << std::endl;
}
Output
123 123
Why is the output 123 123
and not 10 123
?
Also: what is the difference between int x {10};
vs int x = 10;
?
CodePudding user response:
rx
is a reference (alias) to x
. Reading a value from rx
will read the value from x
instead. Assigning a value to rx
will assign the value to x
instead. rx
is not an actual variable with storage, it has no value of its own.
As for initialization:
int x {10};
is using Direct Initialization syntax:
Initializes an object from explicit set of constructor arguments.
int x = 10;
is using Copy Initialization syntax:
Initializes an object from another object.
CodePudding user response:
&rx=x
which means that rx is reference'application you another name of x so r