On Thu, 08 Jan 2004 15:02:12 +0530, user wrote:
Well when I tried this exercise I expected the code to fail in the
compilation phase with an error ( not a warning). It did not, and the output
made me think how is this possible to have 2 different value when I am
pointing to the same memory location? I exptected the output to 2 100s or 2
200s. Is 'num' variable pointing some where ????
I'll try to explain this way:
#include <stdio.h>
int
main (void)
{
const int num = 100;
int *ip;
ip = (int *) #
*ip = 200;
printf ("value of num is %d(%d) \n", num, *ip);
printf ("address of ip is 0x%p\n", ip);
printf ("address of num is 0x%p\n", &num);
}
this will print out the addresses the pointers are pointing to.
The output is as expected: the address is the same.
Now, I'm not sure of what i'm about to say, but well, correct me if
I am wrong :)
I *think* that the problem is in what we had declared constant, or, better,
in what the compiler sees as a constant.
const int num = 100, we have declared the variable num, it's *name*,
to be constant. We cannot change the value *through that symbol*,
but nothing prevents us by changing it by other means.
Let's assume this declaration is the same as
int *const num = 100;
This is a constant pointer.
You cannot change it's address, but you can change the data.
The other way is
const int *num = 100;
Here the data is constant, we cannot change the data but we can change the
address the variable points to.
So, AFAIK, it may be correct to make the assumption that when we declare
a
const int num
we are actually declaring (or the compiler is actually going to change it
to) the former:
int *const num
that is a constant pointer. But sintactically we handle it as a normal
variable, with the constraint that we cannot change it's value
*through the symbol itself*, and being it a normal variable, and not a
pointer, we cannot either directly change it's address. But indirectly
we can.
So accessing it by
num = 100;
is only a sintactical error, because the compiler knows that that
*variable name* is constant.
I mean, I *think* that the compiler doesn't make assumptions on the data
pointed by that name, but only on the name itself.
Bye
Daniele "tinybyte" Milan