negative indexes into arrays in C

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
carbonBased

negative indexes into arrays in C

Post by carbonBased »

Perhaps an odd question:

How portable are negative indexes into an array in ANSI C?

In my memory management routines, I have two different kinds of stacks, one is expand up, and one expand down.  The expand up is obviously no problem... the stack pointer increases.  However, the expand down has the pointer starting at 0, and "increasing" into the negative side of zero.

In essence, stack[-1] is the second element in the stack.

This works in GCC perfectly fine... however, is this behaviour defined in ANSI C, or is GCC simply smart enough (or clueless enough...) to allow it to work?

I'm assuming that any/all C compilers will interpret array[index] into *(char *)(array + index), therefore, as long as index is signed, this should work.

Thanks,
Jeff
AnotherNewOS

RE:negative indexes into arrays in C

Post by AnotherNewOS »

Hi !

That sounds VERY SCARY to me.
I think you should better not use negative indexes on arrays.

IF the compiler makes that right, the danger of using
an unsigned if quite very high ...

Joerg
Post Reply