Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c - Where constants are stored in memory?

In the code given below, I haven't declared any variable that means I have used 0 bytes or constants are declared in the ROM as in the case of string literal.

#include <stdio.h>

//Compiler version gcc  6.3.0

int main()
{
  printf("%d",2*5);
  return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 adds x 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...