In C, constants can be divided into several types, primarily literal constants (Literal Constants) and symbolic constants (Symbolic Constants). The storage location of these constants depends on their type and purpose.
-
Literal Constants: For example, numbers like
123, characters like 'a', and strings like "hello" are typically stored in the program's read-only data segment. This is because the values of literal constants are determined at compile time and remain unchanged during program execution. -
Symbolic Constants: Constants defined using the
#definepreprocessor directive or theconstkeyword. Their storage location may vary slightly:-
Constants defined with
#define: The preprocessor replaces all symbolic constants with their values during preprocessing. Consequently, they do not occupy storage space; instead, they are directly substituted with their values at each usage point. -
Constants defined with
const: These constants are typically stored in the program's data segment, specifically in the read-only data segment or other segments depending on the compiler's implementation. Although variables defined withconstare logically not modifiable, the compiler typically allocates storage space to enable access via pointers or similar mechanisms.
-
For example, consider the following constants defined in a C program:
c#define PI 3.14159 const int maxScore = 100;
-
PIis replaced with3.14159at every usage point, consuming no additional memory. -
maxScoremay be stored in the read-only data segment, with the exact location depending on how the compiler handles global variables declared withconst.
Understanding the storage location of constants aids in better comprehension of memory management and program performance optimization.