...
The C programming language has several mechanisms for creating named, symbolic constants: const
-qualified objects, enumeration constants, and object-like macro definitions. Each of these mechanisms has associated advantages and disadvantages.
const
-Qualified Objects
Objects that are const
-qualified have scope and can be type-checked by the compiler. Because these are named objects (unlike macro definitions), some debugging tools can show the name of the object. The object also consumes memory.
...
const
-qualified objects are likely to incur some runtime overhead [Saks 2001b]. Most C compilers, for example, allocate memory for const
-qualified objects. const
-qualified objects declared inside a function body can have automatic storage duration. If so, the compiler will allocate storage for the object, and it will be on the stack. As a result, this storage will need to be allocated and initialized each time the containing function is invoked.
Enumeration Constants
Enumeration constants can be used to represent an integer constant expression that has a value representable as an int
. Unlike const
-qualified objects, enumeration constants do not consume memory. No storage is allocated for the value, so it is not possible to take the address of an enumeration constant.
...
Enumeration constants do not allow the type of the value to be specified. An enumeration constant whose value can be represented as an int
is always an int
.
Object-like Macros
A preprocessing directive of the form
#
define
identifier replacement-list
defines an object-like macro that causes each subsequent instance of the macro name to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive [ISO/IEC 9899:2011].
...
Macros can be passed as compile-time arguments.
Summary
The following table summarizes some of the differences between const
-qualified objects, enumeration constants, and object-like macro definitions.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard | DCL06-CPP. Use meaningful symbolic constants to represent literal values in program logic |
---|---|
ISO/IEC TR 24772 | "BRS Leveraging human experience" |
MITRE CWE | CWE-547, "Use of hard-coded, security-relevant constants" |
...