Discussion in "General help Guidance and Discussion" started by    mohansaini    Mar 28, 2014.
Fri Mar 28 2014, 12:22 pm
#1
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.
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
#2
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.
 mohansaini like this.
Mon Mar 31 2014, 02:37 pm
#3
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
#4
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
#5
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

Get Social

Information

Powered by e107 Forum System

Downloads

Comments

Darrellciz
Thu Apr 18 2024, 11:07 am
Charlessber
Thu Apr 18 2024, 09:29 am
BartonSem
Thu Apr 18 2024, 04:56 am
DonaldKnown
Thu Apr 18 2024, 12:24 am
utaletxcyw
Wed Apr 17 2024, 10:21 am
Anthonyvab
Wed Apr 17 2024, 08:48 am
RobertCix
Wed Apr 17 2024, 06:46 am
Astorne
Tue Apr 16 2024, 08:52 pm