Possible Duplicate:
“static const” vs “#define” in c
In C are symbolic constants defined at compile time or runtime?
Whats the difference between symbolic constant:
#define GOKU 9111
vs const variables
int const GOKU = 9111;
Possible Duplicate:
“static const” vs “#define” in c
In C are symbolic constants defined at compile time or runtime?
Whats the difference between symbolic constant:
#define GOKU 9111
vs const variables
int const GOKU = 9111;
A define
is simply a text replacement. A const
is read-only memory. For instance, you can't say &GOKU
if it's a define.
EDIT
I forgot about type checking and scoping. Using const
is sometimes better than using a define
since the compiler can check the types if you involve the constant in an operation. Also const
obeys scopes so it won't pollute your namespace.
The most obvious difference is that #define is processed by the preprocessor, whereas const is processed by the compiler. None of them are defined at runtime. When using a #define, the literal GOKU will be replaced in your source code with 9111, after which the compiler will do its job.
Preprocessor constants exist only before the compilation. In fact, they are all resolved during preprocessing and (iin case you want to) you can perform only preprocessing and look at the result.
Const variables, on the other hand, remain in compiled programs, and thus can be sought out at the linking stage. For example, you could define "extern int const GOKU" in another file and then link it together with your first one to access GOKU.
Note that if you tried including file with const variable, it could led to error like "symbol GOKU is defined multiplie times".
There is also difference in visibility. While constant variable follows the rules of nested namespaces (that is, for exmple: if it is global, it will be seen everywhere in the file, but it can be redefined inside any blok of code ), preprocessor constantis visible from the line where it is defined to the line where it is undefined (or the end of file). Naturally, you can undefine (with #undef) or redefine (with another #define) it.
There is also the question of how the code is compiled. Using first GOKU would lead to a bit faster code, sine numeric consant would be built in the instructions. Using second GOKU would lead to a bit slower code, as there would be indirection to where the variable is placed in Data segment.
That's all i can immediately recall.