In C, shall I prefer constants over defines? I’ve reading a lot of code lately, and all of the examples make heavy use of defines.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, in general you should not use const-qualified objects in C to create names constants. In order to create a named constant in C you should use either macros (
#define) or enums. In fact, C language has no constants, in the sense that you seem to imply. (C is significantly different from C++ in this regard)In C language the notions of constant and constant expression are defined very differently from C++. In C constant means a literal value, like
123. Here are some examples of constants in CConstants in C can be used to build constant expressions. However, since const-qualified objects of any type are not a constants in C, they cannot be used in constant expressions, and, consequently, you cannot use const-qualified objects where constant expressions are required.
For example, the following is not a constant
and since the above
Cis not a constant, it cannot be used to declare an array type in file scopeIt cannot be used as a case label
It cannot be used as bit-field width
It cannot be used as an initializer for an object with static storage duration
It cannot be used as a enum initializer
i.e it cannot be used anywhere where a constant is required.
This might seem counter-intuitive, but this is how C the language is defined.
This is why you see these numerous
#define-s in the code you are working with. Again, in C language const-qualified object have very limited use. They are basically completely useless as “constants”, which is why in C language you are basically forced to use#defineor enums to declare true constants.Of course, in situations when a const-qualified object works for you, i.e. it does what you want it to do, it is indeed superior to macros in many ways, since it is scoped and typed. You should probably prefer such objects where applicable, however in general case you’ll have to take into account the above limitations.