Re:Introducing MIR
by munificent on Wednesday April 27, 2016 @04:28PM
(#11584241)
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:
Re:Introducing MIR
by jeffdavis on Thursday April 28, 2016 @03:55AM
(#11587136)
For 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".
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:
You could make the pointer arithmetic more explicit like this: But I think that's needlessly verbose.[1]: https://github.com/munificent/wren/blob/master/src/vm/wren_v...