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
constmeans 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
| Declaration | Read right to left | *p = 5; | p = &y; |
|---|---|---|---|
int *p | p is a pointer to int | Yes | Yes |
const int *pint const *p | p is a pointer to a const int | No | Yes |
int *const p = &x | p is a const pointer to int | Yes | No |
const int *const p = &x | p is a const pointer to a const int | No | No |
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 *pandint const *pare 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
ptc(pointer to const) moved from x to y, but writing*ptc = 5would be a compile error.cp(const pointer) changed x through*cp, but can never point to anything else.cpccan only read.- The lines in comments show the errors GCC reports if you uncomment them.
xitself 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 knowsmarksis safe.fill(int *const buf, ...): the function can write the elements but can't accidentally movebuf.- To point at a
const intlikeMAX, useconst int *. A plainint *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
| Mistake | What happens | Fix |
|---|---|---|
Thinking const int *p means p can't move | Wrong interview answer | It locks the value |
int *const p; without a value | Error/useless: can't assign later | Initialize: int *const p = &x; |
int *p = &MAX; where MAX is const | Warning: discards const | const int *p = &MAX; |
Writing through a const char * parameter | Compile error | Remove const only if the function must modify |
| Believing const makes the variable itself const | Confusion when it changes | It only limits access through that pointer |
const Pointers Practice Questions
- What is the difference between
const int *pandint *const p? - Are
const int *pandint const *pthe same? - Why must a const pointer be initialized when declared?
- Which of
*p = 1andp = &yis allowed forconst int *const p? - Why do string functions use
const char *parameters?
Show answers
- The first can't change the value through p (but can move); the second can't move (but can change the value).
- Yes, identical.
- It can never be assigned afterwards, so it must get its address at declaration.
- Neither.
- 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)
-
In
const int *p;, which is not allowed?A)
p = &y;B)*p = 5;C)printf("%d", *p);D)p++; -
In
int *const p = &x;, which is not allowed?A)
*p = 5;B)p = &y;C)x = 3;D)printf("%d", *p); -
int const *pis the same as:A)
int *const pB)const int *pC)const int *const pD)int *p -
A constant pointer to a constant integer is:
A)
const int *pB)int *const pC)const int *const pD)int const p -
The parameter of
strlenis:A)
char *sB)const char *sC)char *const sD)void *s
Show answers
- B:
*p = 5; - B:
p = &y; - B:
const int *p. - C:
const int *const p. - 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 *p | Pointer to const: value locked |
|---|---|
| int const *p | Same as const int *p |
| int *const p | Const pointer: pointer locked, must initialize |
| const int *const p | Both locked |
| Reading rule | Right to left from the name |
| Quick rule | const 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.