4 ms·
I actually use negative indices in real code[1]. If you implement a stack using an array and you track the top of stack by a pointer just past the last element
by munificent 11y ago
I actually use negative indices in real code[1].
If you implement a stack using an array and you track the top of stack by a pointer just past the last element, then you can index negatively into that pointer to access items on the stack:
// Create an empty stack.
int stack[100];
int* top = &stack;
// Push a couple of values.
*top++ = 123;
*top++ = 456;
// Peek the values.
printf("%d\n", top[-1]); // 456.
printf("%d\n", top[-2]); // 123.
You could make the pointer arithmetic more explicit like this:
printf("%d\n", *(top - 1)); // 456.
But I think that's needlessly verbose.
[1]: https://github.com/munificent/wren/blob/master/src/vm/wren_vm.c#L628 https://github.com/munificent/wren/blob/master/src/vm/wren_v...
- jeffdavis 11y agoFor something like that, I would use the explicit pointer arithmetic. The array syntax implies (to me) "I am doing the normal thing with this normal array".