const char is a special snowflake, it behaves a little differently as a friendly syntax thing for C and C-strings.
lets take a look at an integer, to be more sure of it all.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
#include<memory.h> //what happened here? Ill look it up but <cmemory> and <memory> were both rejected on my box.
usingnamespace std;
int main()
{
constint n[] = {1,2,3};
int * ip;
unsignedlonglong derp;
derp = (unsignedlonglong)(&n[0]);
memcpy(&ip,&derp, sizeof(longlong));
ip[0] = 5;
cout << n[0] << endl;
}
result:
5
basically, the pointer becomes just an integer value for a moment and the const is lost. There are other ways to do it, this is the low level 'take an axe to it' way.
well, of course. you can't answer the question and 'it can't be done' if you want to be THAT way about it lol. But there I am, doing the undoable ;) with an unmitigated hack. It works because undefined is so very often quite predictable, more than anything else.
Add that to the pile of "// THIS WORKS DON'T TOUCH IT" code.
Edit: Funny enough, jonnin's code compiles to
1 2
mov eax, 5
ret
with any optimization level turned on.
I wouldn't rely on such behavior for a more complicated function. (The real fun might happen when compiling different translation units, I think that some fun could be had there)
I wouldn't rely on such behavior for a more complicated function.
I would not either, this sort of stuff is unreliable even across compiler and OS versions on the same platform. Hopefully we all know the snippet was for entertainment only? I am a bit fast and loose on the undefined stuff (I can't even remember a lot of what is and what isn't) and even I would never recommend actually DOING this outside of playing.
Crashes here
I would be amazed if it worked on over 50% of modern platforms, to be honest.
If it crashes on something, double check the pointer vs int type sizes make sure your pointer and int size match. If it still fails after that, would have to dig into why.