Read-Only Pointers

With a pointer parameter, a function can change the caller's variables. That's useful, but it's also a risk: a function that should only read an array could change it by mistake. And whoever reads the first line int sum(int *numbers, int count) can't tell whether the function changes the array or not.

The keyword const solves both problems. You know it from constants such as const double VAT = 0.21;: a value that must not change. Before the type of a pointer, it means that the values must not be changed through this pointer:

int sum(const int *numbers, int count) {
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += numbers[i];
    }
    return total;
}

Read const int *numbers as "numbers points to whole numbers that it may only read". The array you pass doesn't have to be const: the promise applies only inside the function. When the function tries to change it anyway, for example with numbers[0] = 0;, compiling ends with the error read-only variable is not assignable. So write const whenever a function only reads an array. Its first line then says so, and the compiler makes sure of it.

You've seen this before: the parameter const char text[] from the lesson on functions is the same as const char *text.

With strings, const has one more use. A pointer can also point to text in quotes:

#include <stdio.h>

int main(void) {
    char word[] = "cat";
    word[0] = 'h';
    printf("%s\n", word);

    const char *pet = "dog";
    printf("%s\n", pet);
    pet = "fish";
    printf("%s\n", pet);
    return 0;
}

This prints:

hat
dog
fish

char word[] = "cat"; creates an array and copies the text into it. The array is yours, so you can change its letters. const char *pet = "dog"; creates no array of its own: the pointer only points to the text in quotes, and that text is stored in a part of memory that the program must not change. That's why const belongs before it. Then pet[0] = 'f'; is a compile error (read-only variable is not assignable), but you can point pet to other text: pet = "fish";. C also lets you write char *pet = "dog"; without const, but changing the text through such a pointer is a bug: on a computer, the program usually crashes.

Instructions

The function count_passed only reads the array. Change its parameter to const int *scores. The program still prints Passed: 3.

The function print_title only reads the text, and text in quotes must not be changed anyway. Change its parameter to const char *title.

Below count_passed, write a function best that gets the scores as const int *scores and their count, and returns the highest score. In main, below the last printf, print Best: and the result of best(scores, 5). The program prints Best: 90.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

10/11