I'm working through a book called C Programming: A Modern Approach and in the first section discussing arrays, the author states:
using a macro to define the length of an array is excellent practice
Then uses the brief example:
#define N 10
...
int a[N];
I understand that it has something to do with being able to go back into the source code of the program and change the value, and making it a macro maybe makes it easier for the programmer, but I'm not certain. Why is this an excellent practice, or is it objective?
It's a good practice because
That being said I'm not sure I agree this is the best way. An enum also works and avoids some of the problems with macros (e.g. harder to overwrite and silently compile). And IIRC a const int
works as well.
For reference this compiles with cc
:
const int s = 1;
int a[s];
int main() {
return 0;
}
Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin12.4.0
Thread model: posix
It is a very good practice, the C language specification itself says to NEVER bury constants into code, but to define them with meaningful names. There are a few ways to do it, macros (my personal favorite since they use no memory), globals (use memory and can be modified), constant globals (use memory but never change).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With