Home > Blockchain >  inability to modify constant when it has defined in another file [duplicate]
inability to modify constant when it has defined in another file [duplicate]

Time:09-17

Recently I learnt I could modify a constant using pointers in C.

I have successfully achieved this if the constant is defined in the same source file where we are trying to update the constant. However, consider we have two files:

File1.c

int const age=34;

File2.c


#include "File1.c"
#include <stdio.h>
#include <stdlib.h>

extern int const age;

int main(void){

       int newAge=2*age;

       int *ptrAge=(int *) &age;
       *ptrAge= newAge;

       printf("Modified age is %d", age);
        
       return 0;
}

This does not seem to compile because I am getting an error saying: "The instruction [some address] referenced memory at [some address]. the memory could not be written".

Does anyone know how can we change a constant defined in another file?

Many thanks

CodePudding user response:

Recently I learnt I could modify a constant using pointers in C.

False

I have successfully achieved this if the constant is defined in the same source file where we are trying to update the constant.

You did not successfully do it. You invoked undefined behavior. And since undefined behavior means the behavior is not defined, it may work the way you intended. Maybe it crashes the next time you execute it. Or if you recompile it with other flags, or another version, or run it on another computer. Etc...

What is Undefined Behaviour in C?

  • Related