165k views
2 votes
Why should you use a named constant for the size of an array?

User Kit Ramos
by
8.0k points

1 Answer

4 votes
I can think of the following reasons:

- Avoid magic numbers. The constant will have a descriptive name like "MAX_MEASUREMENTS" so it can be inferred what the array size really means.

- Avoid duplication. There could be some related code (e.g., code that checks if an index is within the array bounds) that can benefit from using the same constant. Then it makes sense to tie them together such that if you change the constant, you're actually changing all its occurrances.

- Central configuration. By placing all your constants in a centralized place in the code, it is clear to see where your configuration resides. This is easier than having magic numbers scattered throughout the code.
User Rahul Prasad
by
8.2k points