typestar

tour_header.c en C

Un header y su implementación en un archivo, mostrando la división de un proyecto real.

/* ---- 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;
}

Cómo funciona

  1. La sección de header con guarda declara el tipo casi opaco y su API.
  2. La sección de implementación define lo que el header prometió.
  3. main usa solo lo que el header expone.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
68
Caracteres a escribir
1498
Tokens
403
Ritmo de tres estrellas
105 tpm

Al ritmo de tres estrellas de 105 tokens por minuto, este intento toma unos 230 segundos.

Escribe este fragmento

Paso 1 de 1 en Bis; paso 12 de 12 en Preprocesador y encabezados.

← Anterior