How do I prevent the MSVC compiler from replacing const with immediate value

95 views Asked by At

I am trying to make the following contrived example work. In the code below, I declare a const global variable and attempt to modify it by first using VirtualProtect to make the address writable.

#include <cstdio>
#include "windows.h"

int const ConstantZero = 0;

int main() {
    DWORD OldProtect = NULL;
    VirtualProtect((void *)&ConstantZero, sizeof(int), PAGE_READWRITE, &OldProtect);
    const_cast<int&>(ConstantZero) = 1;
    printf("ConstantZero is %d\n", ConstantZero);
}

While this works, the argument to the printf function is passed as an immediate value, rather than a variable. Is there anyway to make the compiler pass the argument as a variable instead? I am using MSVC compiler version 19.26.28806 for x86.

0

There are 0 answers