What is the output of this code ?
#include <iostream>
using std::cout, std::endl;
int main() {
int i = 1;
{
int& i = i;
i += 1;
}
cout << i << endl;
}
The code actually can be compiled, but compiler raises some error about uninitialized reference i for the following line :
int& i = i;
Then during execution, we may get a segmentation fault error : the program initializes the reference int& i with itself, and cannot actually bind it to the int i variable defined at the first line of the main function.
It's a limitation of C++ (but tbh, this case is kinda weird and not really a good coding example). To correct it, one can consider another naming for the reference, for instance :
int& _i = i;
_i += 1;
then it would modify the i value as expected and output 2 in the terminal when executing the code.