#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.
没有评论:
发表评论