why are magic numbers preferred?

Cristian Ionescu-Idbohrn cristian.ionescu-idbohrn at axis.com
Thu Apr 17 18:51:16 UTC 2008


On Thu, 17 Apr 2008, Denys Vlasenko wrote:

> On Wednesday 16 April 2008 17:59, Cristian Ionescu-Idbohrn wrote:
>
> > Please consider the 1st attachment as a POC, and then the 2nd
> > attachment, which is more dearer to me ;-)
>
> Named constants should be used if values they represent
> are difficult to remember and/or when they can change
> (or be variable across architectures, etc).

Sorry Denys, but...

I think named constants should _also_ be used _to make_ the values they
represent easily replaceable.  Suppose the block size in
archival/libunarchive/get_header_tar.c is suddenly changed from 512 to
1024.  It then _must_ be easier to change one constant in some header file
instead of grepping through the whole tree for the old hard coded value,
analyze it (does it realy refer to the block size) and hard code again.

What do you say?

> Values which are round and frozen (like tar block size)
> don't generally need this. It only obscures the code.

I would say no^H^H maybe ;-)  Depends who the maintainer is.
In this case I think constants like (for example):

#define ONE_K	1024
#define HALF_K	(ONE_K / 2)
#define FOUR_K	(ONE_K * 4)

and so on, would make life easier (grepping none the less).


Cheers,

-- 
Cristian



More information about the busybox mailing list