Constants are stored in various places:
- Constants may be stored in a designated section of memory that is marked read-only for the program.
- In general-purpose systems, this is not ROM. ROM is physically read-only memory. ROM is typically used in special-purpose systems where the software is set prior to manufacturing the hardware (or at least prior to making the ROM devices). General-purpose systems use RAM for read-only portions of programs. It is writeable so the operating system can load the program and its data. After the program is loaded, the operating system configures settings for hardware features that prevent the program from modifying the RAM.
- Various kinds of constants may be stored together, mixing strings and number and other information, or they may be organized by various characteristics, such as storing all eight-byte constants in one section and four-byte constants in another, to make managing alignment and padding easier or more efficient. Also, some constants may be shared; if you use the number 921,123,537 in one source file and also in another, we would generally like memory to be used for that only once unless language semantics preclude it.
- Constants may be built into instructions as immediate operands. In many architectures, instructions can include short literal values encoded with the instruction. So an instruction might say “Add 5 to register 4.”
- Constants may be incorporated into the program generally.
- If you multiply
x
by 2, the compiler might generate an instruction that addsx
to itself. So the number 2 never appears in the generated code. - The compiler might rewrite an expression, calculating parts of it or expressing it in different ways. Generally, you should expect expressions built from constants, such as
3*4+5
, to be evaluated at compile time, resulting in the result 25 being in the program somewhere, while the numbers 3, 4, and 5 will not appear in the program. If the compiler is able to reduce an expression further, some constants might vanish or coalesce.
- If you multiply
solved Where constants are stored in memory?