Assigning values to constants - Solution

Previous | Home

The answer is quite simple really. The compiler, when it encounters constant variables has a few options as to how to deal with it. It can,

The first option is possible only in cases where the constant is initialized with a constant expression. For eg.,

const int c = 10;

Here, every instance of the identifier 'c' in the program can now be replaced with the value '10' which is exactly what happens in our case. This of'course is subject to the various scoping rules. In our program every occurance of 'c' is replaced with the constant '10'. But 'p' continues to point to the location of the value '10'. Having been forcefully cast into a non-const pointer to an int, we are able to assign to that location - resulting in the rather puzzling output!

Now the question may arise as to how the compiler treats constant variables initialized with non-const expressions. For eg.,

int i = 10;
const int c = i;

A good way of finding out would be to run a slightly modified version of our program. The listing for this is given below along with the output.

#include <iostream>
using namespace std;

void main()
{
	int i = 10;
	const int c = i;	//initializing with a non-const expression
	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;

	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 = 20
 *p = 20

As is evident from the output the compiler in this case does nothing extravagant and simply allocates memory for the constant. Since we were able to assign to this location using the pointer without a disastrous consequence (such as a memory fault) we can safely assume that the allocation happens in writeable memory. This is so because the constant itself is initialized only at run-time which would naturally require that it is allocated in writeable memory.

Previous | Home

Hosted by www.Geocities.ws

1