Skip to content
StudyFame

const and Pointers in C

const int *p, int const *p, int *const p, const int *const p. Four declarations that look nearly the same, and one of the most common C interview questions: "What's the difference?"

In this lesson you will learn a simple right-to-left reading rule that answers it in seconds, and see why const pointers make functions safer.

What You Will Learn

  • What const means with normal variables.
  • Pointer to const: const int *p.
  • Const pointer: int *const p.
  • Const pointer to const: const int *const p.
  • The right-to-left rule for reading declarations.
  • Using const pointer parameters in functions.

const and Pointers Explained

A pointer has two things that could be locked: the value it points to, and the pointer itself (where it points). const can lock either one, or both.

Exam definition: In a pointer to constant (const int *p), the value cannot be changed through p, but p can point elsewhere. In a constant pointer (int *const p), p cannot point elsewhere, but the value can be changed. In a constant pointer to constant (const int *const p), neither can change.

Memory trick: Look at which side of the * the const is on. const before * → the data is locked ("read-only view"). const after * → the pointer is locked ("stuck to one house").

Syntax: Four Declarations Side by Side

DeclarationRead right to left*p = 5;p = &y;
int *pp is a pointer to intYesYes
const int *p
int const *p
p is a pointer to a const intNoYes
int *const p = &xp is a const pointer to intYesNo
const int *const p = &xp is a const pointer to a const intNoNo

The right-to-left rule

Start at the name, read leftwards; say "pointer to" for every *.

int *const p          p  is a  const  pointer to  int
      ^^^^^ ^         ---------> reading leftwards <--------

const int *p          p  is a  pointer to  int  const   (= const int)
int const *p          p  is a  pointer to  const  int   (same thing)
  • const int *p and int const *p are identical.
  • A const pointer (int *const p) must be initialized when declared, because it can't be assigned later.

Example 1: What Each Kind of Pointer Can Do

#include <stdio.h>

int main(void)
{
    int x = 10, y = 20;

    const int *ptc = &x;          /* pointer to const */
    int *const cp = &x;           /* const pointer    */
    const int *const cpc = &y;    /* const pointer to const */

    /* pointer to const: can move, can't write */
    printf("ptc reads x : %d\n", *ptc);
    ptc = &y;                     /* OK: point elsewhere */
    printf("ptc reads y : %d\n", *ptc);
    /* *ptc = 5;    error: assignment of read-only location */

    /* const pointer: can write, can't move */
    *cp = 15;                     /* OK: change x */
    printf("x via cp    : %d\n", x);
    /* cp = &y;     error: assignment of read-only variable 'cp' */

    /* const pointer to const: only read */
    printf("cpc reads y : %d\n", *cpc);
    /* *cpc = 1;    error */
    /* cpc = &x;    error */

    x = 99;                       /* x itself is not const */
    printf("x changed directly: %d\n", x);

    return 0;
}

Output

ptc reads x : 10
ptc reads y : 20
x via cp    : 15
cpc reads y : 20
x changed directly: 99

Code Explanation

  1. ptc (pointer to const) moved from x to y, but writing *ptc = 5 would be a compile error.
  2. cp (const pointer) changed x through *cp, but can never point to anything else.
  3. cpc can only read.
  4. The lines in comments show the errors GCC reports if you uncomment them.
  5. x itself isn't const. const int * means "I won't change it through this pointer", not "nobody can change it".

How const Protects Function Parameters

The most common real use is in function parameters. const char *s in a prototype is a promise: "this function only reads your data". The compiler enforces it.

size_t strlen(const char *s);                 /* only reads s       */
char *strcpy(char *dest, const char *src);    /* writes dest, reads src */

That's why you can pass a string literal to strlen, and why a careless write inside such a function fails at compile time instead of corrupting data.

Example 2: const Parameters and a Fixed Pointer

#include <stdio.h>

int sum(const int *arr, int n)        /* promise: won't modify arr */
{
    int total = 0, i;
    for (i = 0; i < n; i++)
        total += arr[i];              /* reading is fine */
    /* arr[0] = 0;  would be a compile error */
    return total;
}

void fill(int *const buf, int n, int value)   /* buf can't be moved */
{
    int i;
    for (i = 0; i < n; i++)
        buf[i] = value;               /* writing is fine */
    /* buf++;      would be a compile error */
}

int main(void)
{
    int marks[5] = {80, 72, 95, 60, 88};
    int scores[3];
    const int MAX = 100;
    const int *limit = &MAX;          /* the right pointer for a const int */
    int i;

    printf("Sum of marks = %d\n", sum(marks, 5));

    fill(scores, 3, 7);
    printf("Scores:");
    for (i = 0; i < 3; i++)
        printf(" %d", scores[i]);
    printf("\n");

    printf("Max allowed = %d\n", *limit);
    return 0;
}

Output

Sum of marks = 395
Scores: 7 7 7
Max allowed = 100
  • sum(const int *arr, ...): anyone reading the prototype knows marks is safe.
  • fill(int *const buf, ...): the function can write the elements but can't accidentally move buf.
  • To point at a const int like MAX, use const int *. A plain int *p = &MAX; gives a warning, because it would let you change a constant.

Important Points to Remember

  • const int *p = int const *p: value locked, pointer free.
  • int *const p: pointer locked, value free; must be initialized.
  • const int *const p: both locked.
  • Read declarations right to left from the name.
  • const before * → data; const after * → pointer.
  • Use const pointer parameters for inputs a function only reads.

Common Mistakes Beginners Make

MistakeWhat happensFix
Thinking const int *p means p can't moveWrong interview answerIt locks the value
int *const p; without a valueError/useless: can't assign laterInitialize: int *const p = &x;
int *p = &MAX; where MAX is constWarning: discards constconst int *p = &MAX;
Writing through a const char * parameterCompile errorRemove const only if the function must modify
Believing const makes the variable itself constConfusion when it changesIt only limits access through that pointer

const Pointers Practice Questions

  1. What is the difference between const int *p and int *const p?
  2. Are const int *p and int const *p the same?
  3. Why must a const pointer be initialized when declared?
  4. Which of *p = 1 and p = &y is allowed for const int *const p?
  5. Why do string functions use const char * parameters?
Show answers
  1. The first can't change the value through p (but can move); the second can't move (but can change the value).
  2. Yes, identical.
  3. It can never be assigned afterwards, so it must get its address at declaration.
  4. Neither.
  5. To promise (and enforce) that the function only reads the string, which also allows passing literals.

Coding Exercise

Write int count_char(const char *s, char c) that counts how many times c appears in s (it must not modify s), and test it on "programming" with 'g' and 'm'.

Show solution
#include <stdio.h>

int count_char(const char *s, char c)
{
    int count = 0;
    while (*s)
    {
        if (*s == c)
            count++;
        s++;              /* moving s is allowed: only *s is const */
    }
    return count;
}

int main(void)
{
    printf("g: %d\n", count_char("programming", 'g'));
    printf("m: %d\n", count_char("programming", 'm'));
    return 0;
}
g: 2
m: 2

Quick Quiz: const and Pointers (MCQ)

  1. In const int *p;, which is not allowed?

    A) p = &y;   B) *p = 5;   C) printf("%d", *p);   D) p++;

  2. In int *const p = &x;, which is not allowed?

    A) *p = 5;   B) p = &y;   C) x = 3;   D) printf("%d", *p);

  3. int const *p is the same as:

    A) int *const p   B) const int *p   C) const int *const p   D) int *p

  4. A constant pointer to a constant integer is:

    A) const int *p   B) int *const p   C) const int *const p   D) int const p

  5. The parameter of strlen is:

    A) char *s   B) const char *s   C) char *const s   D) void *s

Show answers
  1. B: *p = 5;
  2. B: p = &y;
  3. B: const int *p.
  4. C: const int *const p.
  5. B: const char *s.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

const int *pPointer to const: value locked
int const *pSame as const int *p
int *const pConst pointer: pointer locked, must initialize
const int *const pBoth locked
Reading ruleRight to left from the name
Quick ruleconst before * = data; after * = pointer

Frequently asked questions

What is the difference between a const pointer and a pointer to const?
A const pointer can't point elsewhere; a pointer to const can't change the value it points to.
How do you read int *const p?
Right to left: "p is a const pointer to int".
Why use const with pointer parameters?
To promise and enforce that the function won't modify the caller's data.

Remember

  • Const left of * = read-only view.
  • Const right of * = stuck to one house.

Next Topic

Next lesson: Structures in C. You will start Module 11 and group different data types together with structures.