Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does making a variable a const or final save bytes or memory?

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:

  • Is there any byte save when identifying static variables as constant?
  • If bytes are saved by doing this, why are they saved? How does the program store the variable differently if it is constant, and why does this way need less storage space?
  • If bytes are not saved by defining variables as 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)?
  • Are there only some IDEs/Languages that save bytes with constant variables?

Thanks for any help, it is greatly appreciated.

like image 790
Assafi Cohen-Arazi Avatar asked Jun 02 '17 04:06

Assafi Cohen-Arazi


1 Answers

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.

like image 52
papyDoctor Avatar answered Sep 18 '22 14:09

papyDoctor