by munificent · 10y ago · 0 comments
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_v...