tags:

views:

124

answers:

2

I can only make out the similarities, not the differences....

+7  A: 

A macro takes arguments and (typically) generates actual code, a #defined:d constant is merely a value:

For instance:

#define MAX_NAME_LENGTH 32

versus

#define MAX(a, b)   ((a) > (b) ? (a) : (b))

Of course, it's often better to use actual language-level constants when possible:

enum {
 MAX_NAME_LENGTH = 32
}

or

const size_t MAX_NAME_LENGTH = 32;

These provide better testability, often work better with debuggers (since they're proper 1st-level symbols), and don't rely on text-substitution techniques.

unwind
But do remember that `const` does not make something a compile time constant. For example, you can't use it to declare the size of a statically allocated array.
detly
@detly: right, in C. In C++ you actually can
Eli Bendersky
`MAX_NAME_LENGTH` is also a macro. (It's not a *function-like* macro.) I think a better description would be that macros effectively do just textual substitution.
jamesdlin
A: 

Constants in C (you asked about that) are numerical constants (0, 1, 0x0, 0.1, 1.E-10, ...), integral character constants ('a', '\n', L'A', ...) and enumeration constants (that are of type int!). So the later are the only ones that can be defined by a program.

Variables that are qualified with the const attribute are not constants in the sense of C. (better read the const here as unmutable or invariant)

Macros are just textual replacements that are done during the preprocessing phase. Often standard library headers contain macros that expand to the suitable constant for the corresponding system. Such are e.g NULL, false, true, INT_MAX, CHAR_BIT, ...

Jens Gustedt