Skip to content
  • const with Pointers · C

const with Pointers

LearnViaNotes @learnvianotes· 2 min read

const can protect the pointed-to data, the pointer itself, or both. Read the declaration right to left.

DeclarationRead asChange *p?Change p?
int *ppointer to intYesYes
const int *p (= int const *p)pointer to const intNoYes
int *const pconst pointer to intYesNo
const int *const pconst pointer to const intNoNo
C
#include <stdio.h>

int main(void) {
    int a = 1, b = 2;

    const int *to_const = &a;     /* read-only view */
    to_const = &b;                /* OK: pointer can move */

    int *const fixed = &a;        /* pointer is fixed */
    *fixed = 10;                  /* OK: data can change */

    const int *const both = &b;
    printf("%d %d %d\n", *to_const, a, *both);
    return 0;
}
Output
2 10 2
C — both assignments are compile errors
int main(void) {
    int a = 1, b = 2;
    const int *to_const = &a;
    *to_const = 5;                /* error: read-only */
    int *const fixed = &a;
    fixed = &b;                   /* error: pointer is const */
    return 0;
}

const in function parameters

C
#include <stdio.h>
#include <ctype.h>

/* const promises: "I will only read the characters" */
int count_upper(const char *s) {
    int n = 0;
    for (; *s; s++)                 /* moving the pointer is fine */
        if (isupper((unsigned char)*s)) n++;
    return n;
}

int main(void) {
    char name[] = "Hello World";
    printf("%d\n", count_upper(name));   /* char * -> const char * is implicit */
    printf("%d\n", count_upper("ABC"));
    return 0;
}
Output
2
3

What is the difference between const char *p, char const *p and char *const p?

Can a const variable be modified through a pointer?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report