What is the difference between macro constants and constant variables in C? [duplicate]
Possible Duplicate:
“static const” vs “#define” in C
I started to learn C and couldn't understand clearly the differences between macros and constant variables.
What changes when I write,
#define A 8
and
const int A = 8
?
Macros are handled by the pre-processor - the pre-processor does text replacement in your source file, replacing all occurances of 'A' with the literal 8.
Constants are handled by the compiler. They have the added benefit of type safety.
For the actual compiled code, with any modern compiler, there should be zero performance difference between the two.
Macro-defined constants are replaced by the preprocessor. Constant 'variables' are managed just like regular variables.
For example, the following code:
#define A 8
int b = A + 10;
Would appear to the actual compiler as
int b = 8 + 10;
However, this code:
const int A = 8;
int b = A + 10;
Would appear as:
const int A = 8;
int b = A + 10;
:)
In practice, the main thing that changes is scope: constant variables obey the same scoping rules as standard variables in C, meaning that they can be restricted, or possibly redefined, within a specific block, without it leaking out - it's similar to the local vs. global variables situation.
In C, you can write
#define A 8
int arr[A];
but not:
const int A = 8;
int arr[A];
if I recall the rules correctly. Note that on C++, both will work.
For one thing, the first will cause the preprocessor to replace all occurrences of A with 8 before the compiler does anything whereas the second doesn't involve the preprocessor
精彩评论