const correctness in C
const on a parameter is a promise to the caller, and the compiler enforces it.
size_t count_char(const char *text, char target) {
size_t found = 0;
while (*text != '\0') {
if (*text == target) {
found++;
}
text++;
}
return found;
}
void demonstrate(void) {
char buffer[] = "mississippi";
const char *reader = buffer;
char *const fixed = buffer;
*fixed = 'M';
(void) reader;
(void) count_char(buffer, 's');
}
How it works
const char *pmay not write throughp.char *const pmay not point somewhere else.- Taking
constwhere you can read is the polite signature.
Keywords and builtins used here
charconstcount_chardemonstrateifreturnsize_tvoidwhile
The run, in numbers
- Lines
- 20
- Characters to type
- 330
- Tokens
- 105
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 70 seconds.
Step 2 of 4 in Values & storage, step 28 of 35 in Language basics.