C Stacks
Push and pop recent readings while separating an empty stack from a valid value.
How it works
A stack removes the most recently added item first. A fixed array plus a used count gives it a small, predictable storage bound. used points to the next free position, so valid elements occupy [0, used). Push must reject a full stack before writing; pop must reject an empty stack before decrementing. A boolean return keeps failure separate from an integer reading, including zero. This representation is useful for a small undo history but has no automatic dynamic growth.
Run it locally
Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.
cc -std=c17 -Wall -Wextra -Wpedantic -Werror stacks.c -o lessonOn Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.
Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.
Example
#include <stdio.h>
#include <stdbool.h>
#include <stddef.h>
struct Stack { int data[4]; size_t used; };
static bool push(struct Stack *stack, int value) {
if (stack->used == 4) { return false; }
stack->data[stack->used++] = value;
return true;
}
static bool pop(struct Stack *stack, int *out) {
if (stack->used == 0) { return false; }
*out = stack->data[--stack->used];
return true;
}
int main(void) {
struct Stack stack = {{0}, 0};
if (!push(&stack, 12) || !push(&stack, 25)) { return 1; }
int value = 0;
if (pop(&stack, &value)) { printf("Popped: %d\n", value); }
printf("Remaining: %zu\n", stack.used);
return 0;
}
Expected result
Popped: 25
Remaining: 1
The second pushed value is the first popped value. Both operations take constant work for this representation. The helper contract assumes stack and out refer to valid objects and used remains within its invariant. A public module should hide the representation or validate corrupted state according to its trust boundary.
For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.