Strange C++ Code

I found this piece of code:

#include
using namespace std;
int main() {
const int a = 10;
int *b = (int *)&a;
*b = 20;
cout << a << ā€˜\nā€™ << *b << endl; return 0; } [/sourcecode] 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).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s