typestar

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

  1. const char *p may not write through p.
  2. char *const p may not point somewhere else.
  3. Taking const where you can read is the polite signature.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Values & storage, step 28 of 35 in Language basics.

← Previous Next →