Assigning values to constants!

Previous | Next | Home

What follows is a slightly weird little C++ program. See if you can make out why it behaves the way it does.

The Program

#include <iostream>
using namespace std;

void main()
{
	const int c = 10;
	int *p = (int *)&c;

	cout<<" p  = "<<p<<endl;
	cout<<" &c = "<<&c<<endl<<endl;

	cout<<"Before assignment\n\n";
	cout<<" c = "<<c<<endl;
	cout<<" *p = "<<*p<<endl<<endl;

	*p = 20;	//assigning to a const object?!

	cout<<"After assignment\n\n";
	cout<<" c = "<<c<<endl;
	cout<<" *p = "<<*p<<endl;
}

The Ouput

 p  = 006AFDF4
 &c = 006AFDF4

Before assignment

 c = 10
 *p = 10

After assignment

 c = 10
 *p = 20

As is evident from the output, the pointer 'p' does in fact point to the location of 'c' in memory but quite strangely we are able to assign a value to that location and yet subsequent usage of the constant do not seem to be affected! If you are completely confused please click here.

If you wish to contact me for some reason please write to [email protected].

Previous | Next | Home

Hosted by www.Geocities.ws

1