Course contentsShow
← C
Lesson 493 of 1,2197. PointersFree lesson

Pointer to a constant (`const int *p`)

Pointer to a constant (const int *p)

What you'll learn: How to create a "read-only" window to a variable so you can look at its value but cannot change it through that specific pointer.

The "Look, Don't Touch" Rule

Imagine you are at a museum looking at a famous painting behind a thick sheet of glass. You can see the painting clearly, you can describe its colors to others, and you can even take notes about it. However, you cannot reach through the glass to paint a mustache on the portrait.

In C, a pointer to a constant works exactly like that glass. It gives you a way to point at a piece of data, but it strips away your permission to modify that data using that specific pointer.

How the Syntax Works

To declare this type of pointer, you place the const keyword before the data type:

int health = 100;
const int *ptr = &health;

// This is perfectly fine:
printf("Your health is: %d", *ptr); 

// This will cause a compiler error:
// *ptr = 150; 

Notice where the const is: it is next to int. This tells C that the integer being pointed to is constant. Even though the original variable health is a normal, changeable variable, the pointer ptr treats it as if it were set in stone.

Why Use This?

You might wonder: "Why would I want to limit myself?"

The most common reason is safety during teamwork. When you pass a pointer to a function, you are giving that function the address of your data. If you only want the function to read your data (like a function that prints a report) and not accidentally mess it up, you pass it as a const int *. It’s a contract that says, "I trust you to look at this, but I don't trust you to change it."

Crucially, the pointer itself isn't stuck. You can move the pointer to look at a different variable whenever you like. You just can't use the pointer to edit whatever it is currently looking at.

Key takeaway

A const int *p lets you read the value it points to, but prevents you from modifying that value through the pointer.