...
Code Block |
---|
const int max = 15;
int a[max]; /* invalid declaration outside of a function */
const int *p;
/* a const-qualified object can have its address taken */
p = &max;
|
Wiki Markup |
---|
{{const}}\-qualified objects are likely to incur some runtime overhead \[[Saks 01b|AA. C References#Saks 02]\]. Most C compilers, for example, allocate memory for {{const}}\-qualified objects. {{const}}\-qualified objects declared inside a function body may 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. |
...
Code Block |
---|
enum { max = 15 }; int a[max]; /* OK outside function */ const int *p; p = &max; /* error: '&' on enum 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
.
...
Code Block | ||
---|---|---|
| ||
/* ... */ if (age >>= 18) { /* Take action */ } else { /* Take a different action */ } /* ... */ |
...
Code Block | ||
---|---|---|
| ||
enum { ADULT_AGE=18 }; /* ... */ if (age >>= ADULT_AGE) { /* Take action */ } else { /* Take a different action */ } /* ... */ |
...
Code Block | ||
---|---|---|
| ||
LDAP *ld = ldap_init("localhost""localhost", 1234); if (ld == NULL) { perror(""ldap_init""); return(1); } |
Compliant Solution
...
Code Block | ||
---|---|---|
| ||
#ifndef PORTNUMBER /* might be passed on compile line */ # define PORTNUMBER 1234 #endif #ifndef HOSTNAME /* might be passed on compile line */ # define HOSTNAME "localhost""localhost" #endif /* ... */ LDAP *ld = ldap_init(HOSTNAME, PORTNUMBER); if (ld == NULL) { perror(""ldap_init""); return(1); } |
Exceptions
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Other Languages
This rule appears in the C++ Secure Coding Standard as DCL06-CPP. Use meaningful symbolic constants to represent literal values in program logic.
References
unmigrated-wiki-unmigrated-wiki-markup |
---|
\[[Henricson 92|AA. C References#Henricson 92]\] Chapter 10, ""[Constants|http://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap10.html]"" \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.3.2.1, ""Lvalues, arrays, and function designators,"" Section 6.7, ""Declarations,"" Section 6.7.2.2, ""Enumeration specifiers,"" and Section 6.10.3, ""Macro replacement"" \[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] ""BRS Leveraging human experience"" \[[Saks 01a|AA. C References#Saks 01]\] \[[Saks 01b|AA. C References#Saks 02]\] \[[Saks 02|AA. C References#Saks 02]\] \[[Summit 05|AA. C References#Summit 05]\] [Question 10.5b|http://c-faq.com/cpp/constvsdefine.html] |
...
DCL05-C. Use typedefs to improve code readability 02. Declarations and Initialization (DCL)