Divide and C

Christopher R Volpe volpe at camelback.crd.ge.com
Fri Mar 29 02:30:41 AEST 1991


In article <3508 at inews.intel.com>, bhoughto at hopi.intel.com (Blair P.
Houghton) writes:
|>In article <1991Mar27.185804.7221 at uunet.uu.net>
karln!karln at uunet.uu.net (Karl Nicholas) writes:
|>>    EX: int array[10][10];
|>>        val = 24;
|>>        ++array[val/10][val%10];
|>
|>ANS:    int array[10][10];              /* for example */
|>        int dividend, remainder;        /* to use as array indices */
|>
|>	val = 24;			/* for example */
|>
|>	dividend = val/10;
|>	remainder = val - val*dividend;	/* the definition of `%' */
|>	++array[dividend][remainder];	/* dividend more significant */

Since what Karl obviously wants is the <val>th entry into the
2D array, in "storage-order", this can be done without any divisions
whatsoever. Remember, after you explicitly compute the quotient and
remainder, the compiler is going to do the complete opposite when it needs
to compute the offset from the array indices. Therefore, just bypass both
steps like this:

     (&array[0][0])[val]

I don't think you can get much more efficient than that. "&array[0][0]"
is evaluated at compile time as a pointer to the first int in the 2D array,
and then [val] just offsets it as if it were a regular one-dimensional array.

-Chris

P.S.:
  I was going to suggest the following:
   ((int *)array)[val]

which seems cleaner to me because it doesn't have the "&" and "[]" which
cancel each other out, so to speak. However, I figured someone would
come up with a reason why casting from "pointer to array [10] of int"
to "pointer to int" is not a great idea. Hmm. Considering that
"array[0]" is of type "array [10] of int" which decays to "pointer to int"
in a value context, perhaps we can just say this:
   (array[0])[val]
or, equivantly(?)
   array[0][val]

Anyone care to comment on the strictly-conformingness of the above
four expressions?
                        
==================
Chris Volpe
G.E. Corporate R&D
volpecr at crd.ge.com



More information about the Comp.lang.c mailing list