negative indexes into arrays in C
Posted: Fri Aug 16, 2002 11:00 pm
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
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