Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!crdgw1!camelback!volpe From: volpe@camelback.crd.ge.com (Christopher R Volpe) Newsgroups: comp.lang.c Subject: Re: Divide and C Message-ID: <17988@crdgw1.crd.ge.com> Date: 28 Mar 91 16:30:41 GMT References: <1991Mar27.185804.7221@uunet.uu.net> <3508@inews.intel.com> Sender: news@crdgw1.crd.ge.com Reply-To: volpe@camelback.crd.ge.com (Christopher R Volpe) Lines: 53 In article <3508@inews.intel.com>, bhoughto@hopi.intel.com (Blair P. Houghton) writes: |>In article <1991Mar27.185804.7221@uunet.uu.net> karln!karln@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 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@crd.ge.com