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?
Just as an addition to the answers given so far: Why undefined behaviour? Let's consider a hypothetical implementation of operator++:
As you now use
operator++
, which itself returns a temporary, you return a reference to temporary that doesn't exist any more after after returning – undefined behaviour.Why do you now see 5? Pure technically (still UB!): As
f
andg
look identical they both use identical offsets to the stack's end on being called and as being called immediately one after another they both start at the same stack end – so they will store the temporary at the same stack address, which is where the reference gets bound to. Note that this finally contains the value before last increment, thus 5, not 6.h
does not need any additional values on the stack, thus the value there won't get overwritten – just alike when doing the assignment, so the value is yet retained. You might have seen something totally different if for some reasonh
did use the stack itself...