/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
GS
11 Sept. 2020
*******************************************************************************/
#include <stdio.h>
int main()
{
printf("Hello World\n");
// This does NOT work!
const int i1 = 5;
printf("%d\n", i1);
*const_cast<int*>(&i1) = 6;
printf("%d\n\n", i1); // output is 5, when we want it to be 6!
// BUT, if you make the `const` variable also `volatile`, then it *does* work! (just like we do
// for writing to microcontroller registers--making them `volatile` too). The compiler is making
// assumptions about that memory address when we make it just `const`, but once you make it
// `volatile const`, those assumptions go away and it has to actually read that memory address
// each time you ask it for the value of `i`, since `volatile` tells it that the value at that
// address could change at any time, thereby making this work.
// Reference casting: WORKS! (since the `const` variable is now `volatile` too)
volatile const int i2 = 5;
printf("%d\n", i2);
const_cast<int&>(i2) = 7;
// So, the output of this is 7:
printf("%d\n\n", i2);
// C-style reference cast (oddly enough, since C doesn't have references :))
volatile const int i3 = 5;
printf("%d\n", i3);
(int&)(i3) = 8;
printf("%d\n\n", i3);
// It works just fine with pointer casting too instead of reference casting, ex:
volatile const int i4 = 5;
printf("%d\n", i4);
*(const_cast<int*>(&i4)) = 9;
printf("%d\n\n", i4);
// or C-style:
volatile const int i5 = 5;
printf("%d\n", i5);
*(int*)(&i5) = 10;
printf("%d\n\n", i5);
return 0;
}
/*
Notes:
I've also noticed that the above works when modifying `const` class members
even when they are NOT `volatile`.
- See my "std_optional_copy_test" program! Ex:
https://onlinegdb.com/HkyNyTt4D
Sample output:
Hello World
5
5
5
7
5
8
5
9
5
10
*/