Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  • size of a bit-field member of a structure
  • size of an array (except in the case of variable length arrays)
  • value of an enumeration constant
  • value of a case constant

#define:

  • operates at compile time
  • consumes no memory (though this is not too important)
  • can use in compile-time constant expression
  • uses different syntax; can make mistake with ;
  • can't create pointers to
  • no type checking

const:

  • operates at run time
  • consumes memory (though this is not too important)
  • can't use in compile-time constant expression
  • uses consistent syntax
  • can create pointers to
  • does type checking

If any of these are required, then an integer constant (which would be an rvalue) must be used.

Method

Evaluated at

Consumes Memory

Viewable by Debuggers

Type Checking

Compile-time constant expression

Enumerations

compile time

no

yes

yes

no

const qualification

run time

yes

yes

yes

no

Macros

preprocessor

no

no

no

yes

This recommendation is related to EXP07-A. Do not diminish the benefits of constants by assuming their values in expressions.

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Summit 05|AA. C References#Summit 05]\] [Question 10.5b|http://c-faq.com/cpp/constvsdefine.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.2.2, "Enumeration specifiers," and Section 6.10.3, "Macro replacement"

...