Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a C compiler obligated to always reload const value from memory?

Tags:

I have a const variable in my embedded C program. It's defined and initialized with 0 in program code. It's placed in a special ROM area via linker script. One can change the content of the special area via special programming procedure, but it cannot be changed during main program execution.

The question is whether I have to declare the constant as volatile. If it's not marked as volatile, is the compiler allowed to replace all references to it with 0? Or is it obligated to load it at least once during program execution?

like image 336
mrn Avatar asked Apr 10 '16 12:04

mrn


People also ask

Does const help the compiler?

Only const on an object definition actually makes it immutable. The main point of using const is not to assist the compiler in optimizations but to protect yourself from mistakes.


1 Answers

It looks like your variable is really a constant (i.e. doesn't change during program execution) with a value unknown to the compiler. If this is the case, you can declare it like this:

extern const int variable; 

(i.e. without volatile and without an initializer) and let the linker script or other tools set up the correct value.

The compiler will then be permitted to load it and potentially leave it in a register forever, but not replace it by 0 or any other value at compile time.

like image 163
n. 1.8e9-where's-my-share m. Avatar answered Oct 24 '22 04:10

n. 1.8e9-where's-my-share m.