Home > Back-end >  When is it ever useful to use negative indexing of a C array?
When is it ever useful to use negative indexing of a C array?

Time:11-04

C arrays allow for negative indexing, but I can't think of a use for that, seeing that you'll never have an element at a negative index.

Sure, you can do this:

struct Foo {
   int arr1[3] = { 1, 2, 3 };
   int arr2[3] = { 4, 5, 6 };
};

int main() {
   Foo foo;
   std::cout << foo.arr2[-2] << std::endl; //output is 2
}

But why would you ever want to do something like that? In any case, when is negative indexing of an array necessary, and in what domains would you be doing it in?

CodePudding user response:

Remember that when you index an array, you get the element at index N which is the element at &array[0] sizeof(array[0]) * N.

Suppose you have this code:

#include <stdio.h>
int main()
{ 
    int a[5] = {5, 2, 7, 4, 3};
    int* b = &a[2];
    printf("%d", b[-1]); // prints 2
   
}
  • Related