Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

A major reason to use macros instead of a constant integer literal is that when a value is used in multiple places in code, it's much easier to update a single macro value than to go through and find all of a value's uses to update them.

For example, consider the following code:

int a[10];
...
for(i = 0; i < 10; i++) printf("%d\n", a[i]);
...
myFunc(a, 10); // 10 indicates the size of the array

If you decide later on to change the size of the array, you have to go through and find every instance of 10 where it is used to indicate the size. However, if we do this:

#define N 10
int a[N];
...
for(i = 0; i < N; i++) printf("%d\n", a[i]);
...
myFunc(a, N); // N indicates the size of the array

All you have to do is change the value of N to some new number to change the size of the array, and all of your other code will work correctly.

As far as performance, using a macro will be just as fast as hard-coded constant values, since macros are simply a text-based substitution. During compile time, if the macro N has the value 10, then every instance of N in the C source code will be changed to 10 before actually being compiled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top