Stack
The first place I’ve encountered the concept of LIFO/LILO is…
Homestuck’s Sylladex. Thank you very much.

If you had ever tried problem solving, you’d know they are important.
At very least, Queue for BFS.
I’ve once used Stack with struct for implementing undo function too.
Like, I used both of them literally in the last post.
Stack
LIFO, or Last In First Out.
To be perfectly honest, the names for Stack and Queue perfectly
describe themselves on how they should function so well that
I don’t have to talk more about.
But for the reference, here’s the code in C:
#include <stdio.h>
#include <limits.h> // contains limits for var types
#define ERROR_ARGUMENT_NULL INT_MIN
#define ERROR_OUT_OF_INDEX INT_MAX
#define MAX_SIZE 10
// Function Declaration
int Push(int* const _pStack, int* const _pIndex, int const _value);
int Pop(int* const _pStack, int* const _pIndex);
int Peek(int* const _pStack, int const _pIndex);
Unlike C#, you cannot put functions anywhere in C and C++.
However, you can put function declarations first and definition later.
(Like C#’s delegate)
The names of parameters can also be skipped but they help readability for later.
/// Function Definition
int Push(int* const _pStack, int* const _pIndex, int const _value) {
if (_pStack == NULL || _pIndex == NULL) return ERROR_ARGUMENT_NULL;
if (*_pIndex >= MAX_SIZE) return ERROR_OUT_OF_INDEX;
_pStack[*_pIndex] = _value;
++(*_pIndex);
return 0;
}
int Pop(int* const _pStack, int* const _pIndex) {
if (_pStack == NULL || _pIndex == NULL) return ERROR_ARGUMENT_NULL;
if (*_pIndex <= 0) return ERROR_OUT_OF_INDEX;
return _pStack[--(*_pIndex)];
}
int Peek(int* const _pStack, int const _pIndex) {
if (_pStack == NULL || _pIndex == NULL) return ERROR_ARGUMENT_NULL;
if (_pIndex <= 0) return ERROR_OUT_OF_INDEX;
return _pStack[_pIndex - 1];
}
And Push, Pop, and Peek.
I wonder if calculating array size inside function is possible.
int main() {
int stack[MAX_SIZE] = { 0 };
int index = 0;
Push(stack, &index, 1);
Push(stack, &index, 2);
Push(stack, &index, 3);
Push(stack, &index, 4);
printf("Pop : %d\n", Pop(stack, &index));
printf("Pop : %d\n", Pop(stack, &index));
printf("Peek: %d\n", Peek(stack, index));
printf("Pop : %d\n", Pop(stack, &index));
printf("Pop : %d\n", Pop(stack, &index));
return 0;
}
And the main.
This returns following:
Pop : 4
Pop : 3
Peek: 2
Pop : 2
Pop : 1
Pre operators
I forgot to write this in previous posts but it is worth noting that pre-in/decrement operators are faster than post counterparts.
int i = 0, N = 5;
for (; i < N; i++) // instead of this
for (; i < N; ++i) // use this!
Let’s not forget to check when this switch is plausible and when it is not.
Like, when you are actually reading it.
int i = 0;
while (i < 5) printf("%d\t", i++);
// switching this to ++i would print from 1 instead of 0