when you #define DIM_MIN 3
, you are defining a constant not a variable.
what's the difference?
well, there are many differences actually, but probably the most important one is that, in case of a defined constant, you don't have a piece of memory that can be accessed by the name DIM_MIN
during runtime (program's execution). so you can't change the value DIM_MIN
at runtime. try printing DIM_MIN
with gdb
!
if the name DIM_MIN
is not available at runtime, when is it resolved then?
defined constants are resolved during the preprocessing phase (see the short on Compilers). essentially text substitution happens. that is, when you're defining DIM_MIN
to be 3
, you're telling the preprocessor: "whenever you encounter DIM_MIN
in my code, literally, substitute it with 3
". this happens before your program is compiled.
there are many more differences between defined constants and variables, but I'll leave that to you to search for.
when should you use either?
now that you know the main difference mentioned above, it's probably clear now when to use either.
typically, literal values (e.g., 3
, which is an int
literal) are defined as constants (with #define
) to avoid having magical values appearing in your source code for the sake of enhancing readability and making your code easy to understand.
variables are used when you want to store a value that may change (vary) during runtime.