There is a simple program
#include <stdio.h>
int counter = 3;
const int& f() {
return counter++;
}
const int& g() {
return counter++;
}
const int& h(int w) {
counter = w;
return counter;
}
void main()
{
const int& x = f();
const int& y = g();
const int& z = g();
const int& t = h(123);
counter = 45678;
printf("%d %d %d %d", x, y, z, t);
}
Why its output is 5 5 5 45678? Especially, why x and y are 5? If they are still connected to the counter after initialization, why they are not 45679 or something like?
Your program has undefined behaviour. The return values of
fandgcease to exist at the end of the statements that call them, sox,yandzdon't refer to anything after their declaration.