Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 135 ยท Pointers

const and Pointers

Learn the difference between a pointer to const and a const pointer in C, how to read the declarations, and how const-correct function parameters prevent bugs.

The const qualifier tells the compiler "this must not be changed through this name". With ordinary variables that's simple: const int limit = 5; can't be assigned again. With pointers there are two things that could be read-only: the pointer itself (where it points) and the object it points to (the value at that address). C lets you protect either one, both, or neither, and the position of const in the declaration decides which.

Getting this right is called const correctness, and it's one of the cheapest safety tools C has. A function that takes const char * promises not to modify your string, the compiler enforces that promise, and anyone reading the prototype knows what the function will and won't do. This lesson shows how to read every combination, which conversions are allowed and why one innocent-looking conversion is forbidden, and how to design const-correct functions.

You'll want Pointers fresh in mind; Constants covers const for plain variables.

Reading pointer declarations

Here are the four combinations. The trick for reading them is to start at the variable name and read right to left, saying "pointer to" for each *:

Declaration Read it as Can change *p? Can change p?
int *p p is a pointer to int yes yes
const int *p p is a pointer to an int that is const no yes
int *const p p is a const pointer to int yes no
const int *const p p is a const pointer to a const int no no

The key is which side of the * the const sits on:

  • const left of the * protects the pointed-to value. const int *p and int const *p mean the same thing; both orders are common.
  • const right of the * protects the pointer variable itself.

Here's the rule broken on purpose, so you can see how the compiler reacts. This example does not compile:

C Both kinds of const, violated

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC reports two errors: assignment of read-only location '*reader' for line 8 and assignment of read-only variable 'fixed' for line 9. Notice the wording. "Read-only location" means the target is protected; "read-only variable" means the pointer is. Delete either line and the error for it disappears; delete both and the program compiles (with a harmless "set but not used" warning).

Pointer to const: read-only access

A pointer to const (const int *p) is by far the most useful combination. You can read through it and you can move it around, but you can't use it to change what it points to:

C A pointer to const can move but not write

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The second half shows something people often misunderstand. const int *view does not mean the integer is constant. temperatures[0] is a normal, writable int. The const only restricts what you can do through view. When the array changes, view sees the new value 30. Think of a pointer to const as a read-only window onto data that may or may not be read-only itself.

Pointers to const are also the correct way to point at data that truly is constant:

C
const int max_users = 100;
const int *p = &max_users;      /* fine */
const char *greeting = "hello"; /* string literals must not be modified */

Always use const char * for string literals. C gives literals the type char[] for historical reasons, but writing to one is undefined behavior. With const, the compiler catches the mistake. (GCC's -Wwrite-strings flag makes it warn whenever a literal is stored in a plain char *.)

const pointer: a fixed location

A const pointer (int *const p) always points to the same place, but the value there can change. Like any const variable, it must be initialized when it's declared.

C A const pointer stays put

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program prints bat and then bar: cursor never moves, but every write through it succeeds. Const pointers are less common than pointers to const. You'll mostly see them for pointers that hold fixed hardware addresses in embedded code, or in declarations like const char *const label, which makes a global table entry completely read-only.

Conversions: adding const is free, removing it is not

C lets you add const silently. An int * converts to const int * without a cast, because restricting access can't hurt anyone. That's why you can pass a writable array to a function that takes const int *.

Going the other way discards const, and the compiler warns:

C
const int limit = 5;
int *sneaky = &limit;   /* warning: initialization discards 'const' qualifier
                           from pointer target type [-Wdiscarded-qualifiers] */

You can silence the warning with a cast, int *sneaky = (int *)&limit;, but writing through sneaky is then undefined behavior, because limit really is a const object. The compiler may have placed it in read-only memory, or it may have copied the value 5 into every place that used limit, so the write might crash or seemingly be ignored. Casting away const is only safe when the original object wasn't declared const, which is rare enough that a cast removing const should always make you suspicious.

Why char ** doesn't convert to const char **

Here's a rule that surprises almost everyone. Adding const is fine one level deep (char * to const char *), but not two levels deep. Passing a char ** to a parameter of type const char ** fails; in GCC 14 and later it's an error, passing argument 1 of 'show' from incompatible pointer type.

It's not the compiler being fussy. If that conversion were allowed, you could sneak a write into read-only data without any cast:

C
const char *secret = "read-only";
char *writable;
const char **pp = &writable;   /* imagine this were allowed */
*pp = secret;                  /* fine: *pp is a const char * */
writable[0] = 'X';             /* writable now points into the literal: UB */

What is allowed is char ** to char *const *, or const char * items to const char *const *, because adding const to the middle level closes the loophole: through a char *const * you can't store a new pointer at all. That's why the count_until_null function in Pointers to Pointers uses const char *const *items.

Const correctness in function parameters

The most important place for const is a function's parameter list. A pointer parameter that the function only reads should be a pointer to const. That gives you three benefits at once:

  1. Documentation. The prototype alone tells callers their data won't be changed.
  2. Safety. If you accidentally write through the pointer inside the function, the compiler stops you.
  3. Flexibility. Callers can pass const data, such as string literals or read-only tables. A function taking plain char * would trigger a warning for them.
C A const-correct set of functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

max_of accepts both the read-only fixed_table and the writable readings, because int * converts to const int * for free. clamp_all modifies the array, so its parameter is a plain int *. If you tried to call clamp_all(fixed_table, 3, 0, 100), GCC would warn that the call discards const, and the attempt to write would be undefined behavior.

Notice that count_char does text++ even though text is a const char *. The pointer isn't const, only the characters are, so the function can walk its own copy of the pointer freely.

Top-level const on parameters

Writing void repeat(const int times) or void scan(const char *const text) adds const to the parameter variable itself. Since parameters are copies, that has no effect on the caller at all; it only stops the function body from reassigning its own copy. Some teams like it in function definitions for clarity, but it's noise in prototypes, and the compiler ignores it when comparing a declaration with a definition. The const that matters to callers is the one left of the *.

The standard library follows the same rules

Look at a few prototypes from <string.h> and you'll see const correctness everywhere:

C
size_t strlen(const char *s);
char *strcpy(char *restrict dest, const char *restrict src);
int strcmp(const char *s1, const char *s2);
void *memcpy(void *restrict dest, const void *restrict src, size_t n);

The source arguments are const, the destinations aren't. You can tell what each function reads and writes without reading its documentation. (restrict is a different qualifier, covered in Pointers and Functions.)

There's one well-known gap. strchr and strstr take a const char * but return a plain char *, so they quietly turn a read-only pointer into a writable one:

C
char *strchr(const char *s, int c);

That signature exists so the same function works for both writable and read-only strings, but it means the compiler can't stop you from writing through the result when the input was a literal. C23 fixes this: strchr, strrchr, strstr, strpbrk, memchr and bsearch become qualifier-preserving, so passing a const char * gives you a const char * back. That needs a C library with this part of C23 implemented, which only very recent releases have (the older library on our server doesn't), so treat the result as const yourself whenever the input was const.

Tip: Make const your default for pointer parameters, and remove it only when the function really needs to write. Adding const later to a widely used function is painful, because every caller and every function it calls must be checked; starting const-correct costs nothing.

const with arrays and pointers to pointers

Arrays of pointers combine the rules. Read each one right to left:

C
const char *names[3];          /* array of 3 pointers to const char: strings read-only, slots writable */
char *const slots[3] = {0};    /* array of 3 const pointers to char: slots fixed, text writable */
const char *const days[] = {"Mon", "Tue", "Wed"};   /* nothing changeable */

days is the right type for a fixed lookup table of strings: neither the pointers nor the characters can change, and the compiler can keep the whole table in read-only memory.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given int x = 1, y = 2; const int *p = &x;, which statement compiles?

    const int *p is a pointer to const: you can't write through it, but the pointer itself can be changed to point at y.
  2. 2. What does char *const cursor = buffer; declare?

    const right of the * makes the pointer itself constant. The characters are plain char, so writes like cursor[0] = 'x' are allowed.
  3. 3. With int n = 3; const int *view = &n; n = 9;, what is *view afterwards?

    n is an ordinary int, so changing it directly is fine. A pointer to const only forbids writing through that pointer; it still sees the new value.
  4. 4. Which function signature is const-correct for a function that counts the vowels in a string?

    The function only reads the characters, so they should be const. That also lets callers pass string literals and read-only arrays.
  5. 5. Why is passing a char ** to a const char ** parameter rejected?

    Allowing it opens a loophole for writing to read-only data. char *const * (const on the middle level) is allowed because it closes that loophole.

Summary

  • Read declarations right to left: const int *p is a pointer to const int, int *const p is a const pointer to int.
  • const left of the * protects the pointed-to value; const right of the * protects the pointer variable.
  • A pointer to const is a read-only view: the object itself may still change through other names.
  • Adding const (int * to const int *) is automatic; discarding it gives a warning, and writing to a truly const object through a cast is undefined behavior.
  • char ** doesn't convert to const char ** (that would be a loophole), but it does convert to char *const *.
  • Make read-only pointer parameters const: it documents intent, catches accidental writes and accepts const data.
  • strchr-style functions return a writable pointer from a const one before C23; C23 makes them qualifier-preserving.

Next: void Pointers and Generic Code