tour_header.c in C
A header and its implementation in one file, showing the split a real project makes.
/* ---- tour.h ---- */
#ifndef TYPESTAR_TOUR_H
#define TYPESTAR_TOUR_H
#include <stddef.h>
#define TOUR_MAX_STEPS 64
typedef struct {
const char *slug;
const char *title;
int steps[TOUR_MAX_STEPS];
size_t step_count;
} Tour;
void tour_init(Tour *tour, const char *slug, const char *title);
int tour_add_step(Tour *tour, int tpm);
double tour_average_tpm(const Tour *tour);
#endif /* TYPESTAR_TOUR_H */
/* ---- tour.c ---- */
#include <stdio.h>
#include <string.h>
void tour_init(Tour *tour, const char *slug, const char *title) {
memset(tour, 0, sizeof *tour);
tour->slug = slug;
tour->title = title;
}
int tour_add_step(Tour *tour, int tpm) {
if (tour->step_count >= TOUR_MAX_STEPS || tpm <= 0) {
return 0;
}
tour->steps[tour->step_count++] = tpm;
return 1;
}
double tour_average_tpm(const Tour *tour) {
if (tour->step_count == 0) {
return 0.0;
}
long total = 0;
for (size_t i = 0; i < tour->step_count; i++) {
total += tour->steps[i];
}
return (double) total / (double) tour->step_count;
}
/* ---- main.c ---- */
int main(void) {
Tour tour;
tour_init(&tour, "pointers", "Pointers & memory");
int targets[] = {90, 95, 95, 100, 105};
for (size_t i = 0; i < sizeof targets / sizeof targets[0]; i++) {
if (!tour_add_step(&tour, targets[i])) {
fprintf(stderr, "rejected %d\n", targets[i]);
}
}
printf("%s (%s)\n", tour.title, tour.slug);
printf("%zu steps, average %.1f tpm\n", tour.step_count,
tour_average_tpm(&tour));
printf("rejecting zero: %d\n", tour_add_step(&tour, 0));
return 0;
}
How it works
- The guarded header section declares the opaque-ish type and its API.
- The implementation section defines what the header promised.
mainuses only what the header exposes.
Keywords and builtins used here
charconstdoubleforifintlongmainreturnsize_tsizeofstructtour_add_steptour_average_tpmtour_inittypedefvoid
The run, in numbers
- Lines
- 68
- Characters to type
- 1498
- Tokens
- 403
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 230 seconds.
Step 1 of 1 in Encore, step 12 of 12 in Preprocessor & headers.