Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C support negative array indices?

Tags:

arrays

c

pointers

From this post in SO, it is clear that C supports negative indices.

  1. Why support such a potential memory violation in a program?

  2. Shouldn't the compiler throw a Negative Index warning at least? (am using GCC)

  3. Or is this calculation done in runtime?

EDIT 1: Can anybody hint at its uses?

EDIT 2: for 3.) Using counters of loops in [] of arrays/pointers indicates Run-time Calculation of Indices.

like image 508
boxed__l Avatar asked Aug 11 '13 14:08

boxed__l


People also ask

Does array in C program allows negative index?

It is invalid. By the C standard, it explicitly has undefined behavior.

What will happen if array index is negative?

Python programming language supports negative indexing of arrays, something which is not available in arrays in most other programming languages. This means that the index value of -1 gives the last element, and -2 gives the second last element of an array. The negative indexing starts from where the array ends.

Can array indexes can be negative justify your answer?

No, you cannot use a negative integer as size, the size of an array represents the number of elements in it, –ve number of elements in an array makes no sense.

Why are negative indexes used?

Negative “From the End” Indexing in Python This means the last value of a sequence has an index of -1, the second last -2, and so on. You can use negative indexing as your advantage when you want to pick values from the end (right side) of an iterable.


1 Answers

The calculation is done at runtime.

Negative indices don't necessarily have to cause a violation, and have their uses.

For example, let's say you have a pointer that is currently pointing to the 10th element in an array. Now, if you need to access the 8th element without changing the pointer, you can do that easily by using a negative index of -2.

char data[] = "01234567890123456789";
char* ptr = &data[9];
char c = ptr[-2]; // 7
like image 122
Ziffusion Avatar answered Oct 02 '22 20:10

Ziffusion