Search code examples
variablescompilationconstantslanguage-designinterpretation

Difference between a constant and variable member in compiled or interpreted code


For a while now I have been a little confused about the role of constant members within a language, such as Java or C. I understand that at the source code level, they prevent certain critical members from being mutated and changed, but when compiled or interpreted, is there any difference between them and variable members at all or are they all just pointers to memory addresses?

I thought that perhaps the compiler/interpreter has to implement something special to allow a variable to be mutable, something it wouldn't have to when handling a constant member (perhaps making execution faster or making it use less memory?), is this true or am I completely up the wrong tree?


Solution

  • The const variable and the variable are not stored in the same place once your code is executed. The constant values will go in the flash memory with your program. The variables will go in the flash too but will then be copied in the ram to be modified as your program runs. Making a variable const makes your computer save time and space by not pushing everything in the ram. When you need to modify it, you will push it into the Ram anyway, but most of the time const variables will not be modified. This is in addition to the software fact that you might want to prevent your code to modify a value by mistake.