Rohit kumar Chandel said:
I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
main()
{
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.
In most of the English-speaking world outside India, "doubt" is not
merely a synomym for "question. In international forums like this
one, you'd have a better chance of being understood if you write "I
have a question about the const keyword".
In your program above, the declaration
int *pp = &p;
violates a constraint. For one compiler, it produces a warning
message:
warning: initialization discards qualifiers from pointer target type
You can't legally assign the address of a const object to a non-const
pointer object. This rule exists precisly to avoid the problem you're
seeing. Once the compiler diagnoses the problem, though, it's allowed
to continue to compile the program.
Increase the warning level of your compiler, and pay attention to any
warning messages it produces.
If you really want to modify a const object then ... well, first of
all, you shouldn't try to modify a const object; if you need to modify
it, it shouldn't have been declared const in the first place.
But here's a way to do what you're trying to do:
#include <stdio.h> /* required for printf */
int main(void)
{
const int p = 5;
int *pp = (int*)&p; /* The cast suppresses the warning */
++(*pp);
printf("%d\n", p);
return 0;
}
The cast in effect tells the compiler that you know what you're doing.
This is almost always a bad idea, and the behavior of the program is
undefined. A compiler could *assume* that p is never modified (since
you promised not to modify it) and print 5 even if you've managed to
store the value 6 in its memory location.