A function that returns 1 or 0 tells you whether it worked, but not why it did not. That difference decides what the program should do next. If one input line is malformed, the analyzer should count a rejection and keep reading. If storage is full, it should reject the record but can still print a report. If the machine is out of memory, it should stop cleanly. A single "failed" value forces the caller to guess, and a guess is how a program ends up silently dropping data or giving up on a typo.
An enum names a fixed set of outcomes. Our library will distinguish OK, INVALID, FULL and NOMEM. The library reports what happened; the application decides what to print and whether to stop.
Predict and run
Read the program before pressing Run. Write down its output and explain which statement produces it.
#include <stdio.h>
typedef enum { OK, INVALID } Status;
Status validate(int minutes) {
return minutes >= 1 && minutes <= 180 ? OK : INVALID;
}
int main(void) {
Status status = validate(181);
switch (status) {
case OK: puts("Accepted"); break;
case INVALID: puts("Invalid duration"); break;
}
return 0;
}Check your prediction
Invalid duration181 is above the limit, so validate returns INVALID and the second case runs. Notice that validate only returns a value. It does not print, so a test or a different program can reuse it and choose its own wording.
Give the names a prefix
Enum constants share one namespace with every other ordinary identifier in the file. A short name like OK or FULL collides as soon as two headers both want it. The project therefore spells them ANALYZER_OK, ANALYZER_INVALID and so on. The prefix also tells a reader at the call site which API the value came from.
Each constant has an int value, starting at 0 and counting up. Do not print that number to users or rely on it in output: if someone adds a constant in the middle, every later value shifts. Convert the status to text in one place instead, as shown below.
Let the compiler check the switch
When a switch on an enum has no default, -Wall warns about every constant it does not handle. Suppose you add FULL to the enum and forget one switch:
typedef enum { OK, INVALID, FULL } Status;
void describe(Status status) {
switch (status) {
case OK: puts("Accepted"); break;
case INVALID: puts("Invalid"); break;
}
}warning: enumeration value 'FULL' not handled in switch [-Wswitch]With -Werror this stops the build, which is exactly what you want: the compiler found every place that needs a decision. A default: label would silence the warning for all future constants, so leave it out when you switch over your own enum.
Every case needs an exit
A case label is only a jump target. Execution continues into the next case unless something stops it, usually break or return. Forgetting one is not undefined behavior, it is ordinary C, and it quietly runs two actions:
switch (status) {
case OK: puts("Accepted"); break;
case INVALID: puts("Rejected: bad value");
case FULL: puts("Rejected: storage full"); break;
}With status equal to INVALID, this prints both "Rejected: bad value" and "Rejected: storage full". GCC warns about it under -Wextra, and Clang only with -Wimplicit-fallthrough, so you cannot count on a diagnostic everywhere. The habit that always works is to end each case with break or return.
Fix: one status, two messages
Run this report over all three statuses. Which line is wrong, and which single token fixes it?
#include <stdio.h>
typedef enum { OK, INVALID, FULL } Status;
void report(Status status) {
switch (status) {
case OK: puts("Accepted"); break;
case INVALID: puts("Rejected: bad value");
case FULL: puts("Rejected: storage full"); break;
}
}
int main(void) {
Status results[3] = {OK, INVALID, FULL};
for (int i = 0; i < 3; ++i) {
printf("%d -> ", i);
report(results[i]);
}
return 0;
}0 -> Accepted
1 -> Rejected: bad value
Rejected: storage full
2 -> Rejected: storage fullCheck your fix
Status 1 is INVALID. Its case prints its message and then, with nothing to stop it, runs straight into the FULL case's puts. Add break; at the end of the INVALID case:
#include <stdio.h>
typedef enum { OK, INVALID, FULL } Status;
void report(Status status) {
switch (status) {
case OK: puts("Accepted"); break;
case INVALID: puts("Rejected: bad value"); break;
case FULL: puts("Rejected: storage full"); break;
}
}
int main(void) {
Status results[3] = {OK, INVALID, FULL};
for (int i = 0; i < 3; ++i) {
printf("%d -> ", i);
report(results[i]);
}
return 0;
}0 -> Accepted
1 -> Rejected: bad value
2 -> Rejected: storage fullTurn a status into text at the edge
Write one function that converts a status into a message. Each return exits the switch, so no break is needed:
#include <stdio.h>
typedef enum { STATUS_OK, STATUS_INVALID, STATUS_FULL, STATUS_NOMEM } Status;
const char *status_name(Status status) {
switch (status) {
case STATUS_OK: return "ok";
case STATUS_INVALID: return "invalid input";
case STATUS_FULL: return "storage full";
case STATUS_NOMEM: return "out of memory";
}
return "unknown status";
}
int main(void) {
for (int i = STATUS_OK; i <= STATUS_NOMEM; ++i) {
puts(status_name((Status)i));
}
return 0;
}ok
invalid input
storage full
out of memoryReturning a pointer to a string literal is safe: literals have static storage duration and live for the whole program. Returning a pointer to a local char array would not be, because the array ends with the function call. The final return after the switch covers a value outside the enum, which C does not prevent.
Decide which failure wins
When an input is invalid and storage is full at the same time, the function must still return one status. Pick an order and write it in the contract. This course checks the input first: a bad record is INVALID whether or not there is room. Then a test can state the expected answer for every combination.
Practice
Your turn
A Store keeps up to 3 durations. Write Status store_add(Store *store, int minutes) that returns STATUS_INVALID for minutes outside 1..180 (checked first), STATUS_FULL when 3 values are already stored, and otherwise stores the value and returns STATUS_OK. Failures change nothing. With the starter's calls, the output must be: add 25: ok (1 stored), add 0: invalid input (1 stored), add 30: ok (2 stored), add 40: ok (3 stored), add 50: storage full (3 stored), add 999: invalid input (3 stored).
#include <stdio.h>
#include <stddef.h>
typedef enum { STATUS_OK, STATUS_INVALID, STATUS_FULL } Status;
typedef struct { int minutes[3]; size_t length; } Store;
const char *status_name(Status status) {
switch (status) {
case STATUS_OK: return "ok";
case STATUS_INVALID: return "invalid input";
case STATUS_FULL: return "storage full";
}
return "unknown status";
}
/* Write store_add here. */
int main(void) {
Store store = {{0}, 0};
int inputs[6] = {25, 0, 30, 40, 50, 999};
for (size_t i = 0; i < 6; ++i) {
Status status = store_add(&store, inputs[i]);
printf("add %d: %s (%zu stored)\n", inputs[i], status_name(status), store.length);
}
return 0;
}Hint 1: the idea
The last call, 999, arrives when the store is full. Because input is checked first, the expected status is "invalid input", not "storage full".
Hint 2: a first step
Decide the order of the two failure checks before writing either one, using the last call as your test: with the store full and 999 arriving, which status must win? Write the checks in that order, run, and only then add the store.
Show one solution
#include <stdio.h>
#include <stddef.h>
typedef enum { STATUS_OK, STATUS_INVALID, STATUS_FULL } Status;
typedef struct { int minutes[3]; size_t length; } Store;
const char *status_name(Status status) {
switch (status) {
case STATUS_OK: return "ok";
case STATUS_INVALID: return "invalid input";
case STATUS_FULL: return "storage full";
}
return "unknown status";
}
Status store_add(Store *store, int minutes) {
if (minutes < 1 || minutes > 180) { return STATUS_INVALID; }
if (store->length >= 3) { return STATUS_FULL; }
store->minutes[store->length] = minutes;
++store->length;
return STATUS_OK;
}
int main(void) {
Store store = {{0}, 0};
int inputs[6] = {25, 0, 30, 40, 50, 999};
for (size_t i = 0; i < 6; ++i) {
Status status = store_add(&store, inputs[i]);
printf("add %d: %s (%zu stored)\n", inputs[i], status_name(status), store.length);
}
return 0;
}add 25: ok (1 stored)
add 0: invalid input (1 stored)
add 30: ok (2 stored)
add 40: ok (3 stored)
add 50: storage full (3 stored)
add 999: invalid input (3 stored)The guard order is the documented priority, and the last input proves it. store_add never prints; main turns each status into words through status_name, so a test could compare statuses directly. The checkpoint next combines this with a caller-supplied array and a capacity parameter.
Completion is saved in this browser only. It does not measure mastery.