Guard clauses in C
Validate at the top and return early, so the body has no nesting left.
int copy_bounded(char *dst, size_t cap, const char *src, size_t *written) {
if (dst == NULL || src == NULL || cap == 0) {
return 0;
}
size_t n = strlen(src);
if (n + 1 > cap) {
return 0;
}
memcpy(dst, src, n + 1);
if (written != NULL) {
*written = n;
}
return 1;
}
How it works
- A NULL check at the entrance beats a crash deep inside.
- Early returns keep the happy path at one indent level.
- The checks double as documentation of the contract.
Keywords and builtins used here
NULLcharconstcopy_boundedifintreturnsize_t
The run, in numbers
- Lines
- 14
- Characters to type
- 264
- Tokens
- 94
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 56 seconds.
Step 2 of 4 in Signatures, step 2 of 11 in APIs, errors & testing.