Which one is better to use among the below statements in C?
static const int var = 5;
or
#define var 5
o
In C, specifically? In C the correct answer is: use #define
(or, if appropriate, enum
)
While it is beneficial to have the scoping and typing properties of a const
object, in reality const
objects in C (as opposed to C++) are not true constants and therefore are usually useless in most practical cases.
So, in C the choice should be determined by how you plan to use your constant. For example, you can't use a const int
object as a case
label (while a macro will work). You can't use a const int
object as a bit-field width (while a macro will work). In C89/90 you can't use a const
object to specify an array size (while a macro will work). Even in C99 you can't use a const
object to specify an array size when you need a non-VLA array.
If this is important for you then it will determine your choice. Most of the time, you'll have no choice but to use #define
in C. And don't forget another alternative, that produces true constants in C - enum
.
In C++ const
objects are true constants, so in C++ it is almost always better to prefer the const
variant (no need for explicit static
in C++ though).