#include <iostream>
void inc(long& in){
in++;
}
int main(){
int a = 5;
inc(*reinterpret_cast<long*>(&a));
printf("%d\n", a);
return 0;
}
Above code compiles successfully and prints 6
. Is it undefined behaviour
? as I'm not really making a reference to anything on the stack. I'm doing an inline cast.
Note that this will not work with a normal cast such as static_cast<long>(a)
, you will get a compiler error saying:
candidate function not viable: expects an l-value for 1st argument
Why does *reinterpret_cast<long*>(&a)
compile? I'm dereferencing it to a long
so the compiler should be able to tell it's not referencing anything.
Edit
Ignore the int/long
difference here please, that's not the point of my question. Assume this example if it makes more sense:
void inc(int& in){...}
...
inc(*reinterpret_cast<int*>(&a));
My question is, how is it ok to pass *reinterpret_cast<int*>(&a)
as a reference but static_cast<int>(a)
isn't?