I'm watching a CppCon video, which shows this code:
void foo(const int&);
bool bar(int x)
{
const int y = x + 1;
foo(y);
return y > x;
}
First of all the speaker says that since the foo() function takes 'y' by const reference, and 'y' is actually a const int, then changing the value in foo() is undefined behaviour at runtime. And seems to be saying that since this is illegal the compiler, should actually assume that 'y' doesn't change in the call to foo(), and that the bar() function should just return true without doing the comparison.
The compiler is allowed, as far as I know, to just return true, because it really is illegal for foo() to change 'y'.
Then says "but it doesn't", as if to imply that it's a shortcoming of the compiler which missed out on an optimisation. Is he right about this?
Also, about the assumption that 'y' will always be bigger than 'x' and so the function should just return true instead of comparing them, isn't there a value that can be passed into the function, namely the max value that type can hold, where "y = x + 1" will cause an overflow meaning that y > x is no longer true? This I believe is the case for both signed and unsigned.
So in this example there's signed integers, 'y' is equal to 'x' plus 1, so if 'y' doesn't change, it's now always bigger than 'x'. The compiler's allowed to make that assumption for signed, not unsigned.
He also says:
If you change it to pass by value, then it works.
As if to say that the comparison instruction is gone and the function just returns true, but how can the compiler make this assumption given the integer overflow point?
Here is the relevant point in the video.