ANSWERS: 2
  • "Zero-based indexing" as it is called is slightly more efficient when translated into the assembly language that machines actually execute. for example foo[n] will get the n'th element of array foo. Lets say the elements of foo are 4 bytes each. Then the compilers calculatation of the address will be: address of foo + 4*n. When n is 0 -> foo When n is 1 -> foo + 4 When n is 2 -> foo + 8 etc. In "one-based indexing" the machine has to a little more work because the addressing expression is: address of foo + 4*(n-1).
  • C++ is based on C and C is based on BCPL and in BCPL the following defintions define the array reference operator v*[n] v = lv v*[0] rv v = v*[0] lv v*[n] = v + n 'lv' became '&' in C and 'rv' became the dereference operator '*'. BCPL had no implicit types so v and n are both interchangable machine words. Basing the arrays at zero gives the simplest expression for looking up the value of the element: add the number representing the array to the number representing the index and perform an 'rv' primitive operation. Starting arrays at zero can also help avoid a number of "off by one" mistakes also called "fence-post errors".

Copyright 2023, Wired Ivy, LLC

Answerbag | Terms of Service | Privacy Policy