Strange C++ Code

I found this piece of code:

#include <iostream>
using namespace std;
int main() {
   const int a = 10;
   int *b = (int *)&a;
  *b = 20;
   cout << a << ā€˜\n’ << *b << endl;
   return 0;
}

The output of the above code is 10, 20. Because the compiler, upon finding a constant, does compile time optimizations. Casting away constness is undefined and anything can happen (like sth mentioned above).

Follow

Get every new post delivered to your Inbox.