What is the difference between const and #define?
Short answer: #define is plain text substitution done by the preprocessor before compilation: it has no type, no scope and is invisible in the debugger. const creates a real, typed, scoped object that the compiler checks and that can live in flash (.rodata). Prefer const or enum for type safety, but note that in C a const int is not a compile-time constant expression.
#define N 10 |
const int n = 10; |
enum { N = 10 }; |
|
|---|---|---|---|
| Handled by | preprocessor | compiler | compiler |
| Type | none (text) | int |
int |
| Scope | from definition to end of file (or #undef) |
block or file | block or file |
| Visible in debugger | no | yes | yes (usually) |
Constant expression in C (array size at file scope, case label, static initialiser) |
yes | no | yes |
| Takes memory | no | possibly (often optimised away) | no |
#define BUF_LEN 64
static uint8_t buf[BUF_LEN]; /* fine */
const int len = 64;
static uint8_t buf2[len]; /* error in C (OK in C++): not a constant expression */
C23 adds constexpr for objects, which fixes this: constexpr int len = 64; can size arrays.
Macro pitfalls that const avoids
#define MAX 100 + 1used asMAX * 2gives 102, not 202 (no parentheses, no type).- Macros ignore scope: a
#define count 5in a header silently breaks any variable namedcountafter it. - Error messages show the expanded text, not the macro name.
When #define is still right: conditional compilation (#if DEBUG), constants needed by the preprocessor, include guards, and register addresses in vendor headers. For typed constants (const uint32_t timeout_ms = 500;), lookup tables (static const uint8_t crc_table[256] = {...}; in flash), and groups of related integers (enum state { IDLE, RUN }), use const and enum.