I've been working with a program and I've been trying to conserve bytes and storage space.
I have many variables in my C program, but I wondered if I could reduce the program's size by making some of the variables that don't change throughout the program const
or final
.
So my questions are these:
constant
?constant
, and why does this way need less storage space?constant
, then why would a developer define a variable this way in the first place? Could we not just leave out the const
just in case we need to change the variable later (especially if there is no downfall in doing so)?constant
variables?Thanks for any help, it is greatly appreciated.
I presume you're working on deeply embedded system (like cortex-M processors). For these, you know that SRAM is a scarce resource whereas you have plenty of FLASH memory. Then as much as you can, use the const keyword for any variable that doesn't change. Doing this will tell compiler to store the variable in FLASH memory and not in SRAM.
For example, to store a text on your system you can do this:
const char* const txtMenuRoot[] = { "Hello, this is the root menu", "Another text" };
Then not only the text is stored in FLASH, but also its pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With