Parse a byte, report why it failed
Return a status code and write the result only when parsing succeeded. An easy embedded C problem (Error handling), run and graded in the browser.
easy · Error handling · error-handling · status-codes · parsing
Write parse_u8(s, out), which reads an unsigned decimal number from the text s.
It returns one of:
| Status | When |
|---|---|
ERR_OK | all characters are digits and the value is 0 to 255 |
ERR_EMPTY | the string is empty |
ERR_NOT_DIGIT | any character is not 0 to 9 |
ERR_RANGE | the number is above 255 |
*out is written only on ERR_OK; on any error it keeps its previous value. Check characters in order, so "12x" is ERR_NOT_DIGIT.
Starter code
status_t parse_u8(const char *s, uint8_t *out) {
*out = (uint8_t)atoi(s);
return ERR_OK;
}Example tests
A valid number
show("200");Expected output:
"200": status=0 value=200Empty and not a number
show("");
show("12x");Expected output:
"": status=1 value=99
"12x": status=2 value=99Learn it first
- Error handling and fault strategy · Error codes, assertions, safe states and keeping evidence of what went wrong.
More Error handling problems
- Retry only what can succeed · Repeat an operation while it reports a transient error, but stop on a fatal one.
- Greenhouse: is the water arriving? · Judge each pump run and tell an empty tank from a broken sensor.