A nice macro

Maarten Litmaath maart at cs.vu.nl
Wed Jun 21 07:40:26 AEST 1989


An often-heard complaint by Pascal dweebs on C is the absence of the
equivalence of

	VAR
		foo:	array[-5..-2] of bar;

C arrays always begin with subscript 0.
Some time ago someone (Chris Torek?) suggested to use a macro:

	#define		HIGH		-2
	#define		LOW		-5

	bar	foo[HIGH - LOW + 1];

	#define		foo_addr(n)	&foo[(n) - LOW]

By this scheme every `zork(n)' might be an array reference instead of a
function call/function-like macro invocation. :-(

I doubt Chris was the person who suggested this; the solution below seems so
straightforward:

	bar	_foo[HIGH - LOW + 1];

	#define		foo		(_foo - LOW)

Now:
	foo[-4] == (_foo - -5)[-4] == *((_foo + 5) - 4) == *(_foo + 1) ==
	_foo[1]

There's only one (small) objection: name space pollution - an invisible
extra identifier `_foo' is needed.

Example of the usefulness of negative subscripts: in the MINIX kernel's `proc'
table user processes have positive indices, while kernel tasks have negative.
-- 
"I HATE arbitrary limits, especially when |Maarten Litmaath @ VU Amsterdam:
   they're small."  (Stephen Savitzky)    |maart at cs.vu.nl, mcvax!botter!maart



More information about the Comp.lang.c mailing list