Which one is better to use among the below statements in C?
static const int var = 5;
or
#define var 5
o
If you can get away with it, static const
has a lot of advantages. It obeys the normal scope principles, is visible in a debugger, and generally obeys the rules that variables obey.
However, at least in the original C standard, it isn't actually a constant. If you use #define var 5
, you can write int foo[var];
as a declaration, but you can't do that (except as a compiler extension" with static const int var = 5;
. This is not the case in C++, where the static const
version can be used anywhere the #define
version can, and I believe this is also the case with C99.
However, never name a #define
constant with a lowercase name. It will override any possible use of that name until the end of the translation unit. Macro constants should be in what is effectively their own namespace, which is traditionally all capital letters, perhaps with a prefix.