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.
Variables can have types like Integer or Character. Whereas macros are not variables at all, they are special C directives which are pre-processed before the compilation step is carried out by the compiler to create the object file (binary code of the program).
Description. In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables.
The difference is that #define is processed by the preprocessor doing what amounts to simple text replacement. Const values defined like this are not visible for the actual compiler, while a variable defined with the const modifier is an actual typed "variable" (well not really that variable).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With