Reading history

const and volatile in C: Const Pointers and Parameters

4 min read 0 views

Learn the const qualifier in C: read-only variables, const vs #define, const function parameters, pointer to const vs const pointer, and the volatile keyword.

The const qualifier marks a value as read-only: once set, the program may not change it through that name. It documents your intent, lets the compiler catch accidental changes, and is essential in function parameters, where const int * promises the caller that their data will not be modified. This lesson also covers the four combinations of const with pointers and the related volatile qualifier.

In this lesson you will learn

  • Declaring constants with const
  • const vs #define
  • const parameters as a promise to callers
  • Pointer to const, const pointer, and both
  • What volatile means

See Constants in C for literal values and Pointers in C for pointer basics.

const in Practice

#include <stdio.h>

#define TAX_RATE 0.15                         /* preprocessor text replacement */
static const int MAX_STUDENTS = 60;           /* typed, scoped constant */

static double total_marks(const int *marks, int n) {   /* promise: marks not changed */
    double sum = 0;
    for (int i = 0; i < n; i++) sum += marks[i];
    /* marks[0] = 100;   error: assignment of read-only location */
    return sum;
}

int main(void) {
    int marks[] = {70, 85, 90};
    printf("total %.0f, limit %d, tax %.2f\n", total_marks(marks, 3), MAX_STUDENTS, TAX_RATE);

    int a = 1, b = 2;
    const int *p1 = &a;          /* pointer to const int: *p1 is read-only */
    p1 = &b;                     /* OK: the pointer itself can move */
    int *const p2 = &a;          /* const pointer to int: p2 cannot move */
    *p2 = 50;                    /* OK: the value can change */
    const int *const p3 = &b;    /* neither can change */
    printf("*p1=%d a=%d *p3=%d\n", *p1, a, *p3);

    volatile int sensor = 0;     /* value may change outside the program's control */
    for (int i = 0; i < 3; i++) sensor += i;
    printf("sensor=%d\n", sensor);
    return 0;
}

Output

total 245, limit 60, tax 0.15
*p1=2 a=50 *p3=2
sensor=3
  • static const int MAX_STUDENTS = 60; is a typed constant. Unlike #define TAX_RATE 0.15, it has a type, follows scope rules and is visible in a debugger.
  • In total_marks(const int *marks, int n), const promises that the function only reads the array. Writing marks[0] = 100 would be a compile error, and callers can safely pass read-only data.
  • The position of const relative to * decides what is protected. Read declarations from right to left:
    • const int *p1: “p1 is a pointer to an int that is const”. The value is protected; the pointer can move.
    • int *const p2: “p2 is a const pointer to an int”. The pointer is fixed; the value can change.
    • const int *const p3: both are protected.
  • volatile tells the compiler the variable may change in ways it cannot see, such as a hardware register, a signal handler or memory shared with another device, so every read must really load it from memory instead of reusing a cached value.

Pointer and const Combinations

DeclarationChange *p?Change p?
int *pYesYes
const int *p (same as int const *p)NoYes
int *const pYesNo
const int *const pNoNo

Standard library functions use this pattern constantly: size_t strlen(const char *s) promises not to change your string, while char *strcpy(char *dest, const char *src) changes only dest.

Common Mistakes

  1. Casting const away and modifying the value; if the object was defined const, the behaviour is undefined.
  2. Leaving a const variable uninitialised; it can never be assigned later.
  3. Using a const int as an array size at file scope, which C (unlike C++) does not accept as a constant expression; use #define or an enum there.
  4. Thinking volatile makes code thread-safe; it does not. Use atomics or locks for threads.

Practice Exercises

Exercise 1. Write a function that counts the vowels in a string, with a parameter type that guarantees the string is not changed.

Show answer
#include <string.h>
int count_vowels(const char *s) {
    int n = 0;
    for (; *s; s++)
        if (strchr("aeiouAEIOU", *s)) n++;
    return n;
}

Moving s is allowed, because only the characters are const.

Exercise 2. Which line fails to compile? int x = 1, y = 2; int *const p = &x; *p = 5; p = &y;

Show answer

p = &y; fails, because p is a const pointer. *p = 5; is fine.

Frequently Asked Questions

Should I use const or #define for constants?

Prefer const (or enum for integer constants) because they are typed and scoped. Use #define when you need a true compile-time constant in C, such as an array size at file scope, or for conditional compilation.

Can a variable be both const and volatile?

Yes. const volatile describes something your program must not write but which can change by itself, such as a read-only hardware status register.

Summary

  • const makes a value read-only and lets the compiler enforce it.
  • Use const pointer parameters for data a function only reads.
  • Read pointer declarations right to left to see what is const.
  • volatile forces real memory reads for values changed outside the program’s view.

Next: Command Line Arguments in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *