🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.c.moderated
Article #2283

Re: Pointer Arithmetic

#2283
From: Jens Schweikhardt
Date: Thu, 14 Mar 1996 13:40
38 lines
2290 bytes
In article <4i805f$47d@solutions.solon.com>,
Dan T. Abell <dabell@quark.umd.edu> wrote:
>This may sound like a dumb question, but can someone tell me how C  
>compilers do pointer arithmetic?  In particular, consider an integer array
>	p[0], p[1], ... , p[n]
>whose entry p[k] we might access using *(p + k).  I imagine the typical  
>compiler would multiply the size of an integer by k, add the result to p,  
>and then report the integer located at that address.  Now for my question:  
>Do most compilers use plain ol' multiplication or do they use bit-shift  
>operators.  Also, does the answer depend on the type of the array p?

The answer is, as so often, "it depends".
What the compiler will generate for an int array acces depends on

- the sizeof int, which might well be 3, 5, or 42. Pointer values
  probably wont be calculated with bit shifts here.
  For other types, as you seemed to be ware of, it depends even more :-)
- What the instruction set of the machine supports.
  There may be machines that have instructions to compute
  base+(index * somesize) [I bet there are!]
- How smart the compiler is. Nobody prevents an implementor from
  adding repeatedly 1 to the pointer until it points to the
  desired object. It might not use the efficient instructions mentioned
  above, even when they are available.

If you want to be sure how your compiler does it, trying the -S option
might give an assembler source of your C code. I once investigated it with
gcc on an i486 machine with sizeof int = 4. It does use bit shifts
to compute adresses in int arrays. You don't need to be an assembler
guru to see what's going on in a small program.

To put it in a nutshell:
  You only can be sure by looking at the compiler output.

Bye, Jens

-- 
SIGSIG -- signature too long (core dumped)
Technical Details
Message-ID: <4i97kl$8i5@solutions.solon.com>
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail
References: <4i805f$47d@solutions.solon.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail
From: schweikh@itosun.ito.uni-stuttgart.de (Jens Schweikhardt)
Newsgroups: comp.lang.c.moderated
Subject: Re: Pointer Arithmetic
Date: 14 Mar 1996 07:40:37 -0600
Organization: Comp.Center (RUS), U of Stuttgart, FRG
Sender: clc@solutions.solon.com
Approved: clc@solutions.solon.com
Message-ID: <4i97kl$8i5@solutions.solon.com>
References: <4i805f$47d@solutions.solon.com>
NNTP-Posting-Host: solutions.solon.com