C related question
Discussion in "General help Guidance and Discussion" started by mohansaini Mar 28, 2014.
Fri Mar 28 2014, 12:22 pm
Hello why i can not change a global const variable with a local pointer variable. while if const is local i can change it by a local pointer.
it doesn't work while
works fine what is the reason behind?
const int val1=10; int main() { int *ptr; ptr=&val1; *ptr=5; printf("%d\n",*ptr); }
it doesn't work while
int main() { const int val1=5; int *ptr; ptr=&val1; *ptr=10; printf("%d\n",*ptr); }
works fine what is the reason behind?
Mon Mar 31 2014, 11:52 am
Global constants goes in RO section of the binary hence you cannot change them. whereas when you define a local variable with const attribute and then try to change in your program, you will be able to do it as the memory assigned to local variable is on stack. however if you try to define your local constant as static it goes to the RO section and you will get the same result as that of global constant. i.e. you wont be able to change it.
In terms of C language, this considered as an error as you are trying to assign a constant to a pointer of variable type. C compiler usually throws a warning "warning" to avoid breaking of code.
In terms of C language, this considered as an error as you are trying to assign a constant to a pointer of variable type. C compiler usually throws a warning "warning" to avoid breaking of code.
mohansaini like this.
Mon Mar 31 2014, 02:37 pm
Hi Sir,Thanks for your reply i am asking about first one again what if i declare a pointer globally. can i modify it by global pointer?
Mon Mar 31 2014, 10:12 pm
No you cannot. As I said, global constants are stored in RO (read only) section which cannot be modified.
Wed Apr 02 2014, 02:17 am
The only reason to declare a variable const (constant) is to tell the compiler not to
allow it to be changed.
If you want to change a variable using pointers of any kind, don't declare it const
allow it to be changed.
If you want to change a variable using pointers of any kind, don't declare it const
Powered by e107 Forum System