开发者

What is the difference between symbolic constant and macro in C?

I can only make out the s开发者_如何转开发imilarities, not the differences....


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.


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, ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜