r/cprogramming • u/unintendedbug • Mar 02 '26
Symbolic constants - Best practice
I am currently studying C programming in conjunction with CS50, and I am seeking clarification regarding symbolic constants. I am confused about the appropriate use cases for `#define` macros versus `const` variables, as both mechanisms appear to facilitate the creation of symbolic constants.
7
Upvotes
4
u/[deleted] Mar 02 '26
Constants have scope, type, address and size. Macros have neither of these and work as a primitive text substitution.
3
u/tstanisl Mar 02 '26
There is a third alternative ... anonymous enums:
This methods works for all C standards and all compilers.
If you use C23 compiler (i.e. newer GCC or CLANG) then you can use
constexpr:0
u/zhivago Mar 02 '26
Please ask questions about what confuses you.
1
u/The_Northern_Light Mar 02 '26 edited Mar 03 '26
Use const variables for this, or ideally constexpr
As a general principle, macros are best used only when only a macro can do what you need.
In this case, both solve the problem, so you should prefer the non macro solution.
-4
u/[deleted] Mar 02 '26
I'm guessing you're a bot.
0
u/[deleted] Mar 02 '26
[deleted] — view deleted comment