Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is defining the length of an array with a macro "excellent practice"?

Tags:

arrays

c

macros

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?

like image 260
hancsu Avatar asked Apr 27 '14 18:04

hancsu


2 Answers

It's a good practice because

  • the array size obviously has to be hard-coded
  • but it shouldn't have a magic number injected directly into the source code
  • therefore, a macro is a good way to give it a readable name and remove it from the source

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

like image 145
djechlin Avatar answered Nov 10 '22 22:11

djechlin


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).

like image 43
phyrrus9 Avatar answered Nov 10 '22 20:11

phyrrus9