C const
Pointer
Syntax
const data_type *pointer_name;
Example
#include <stdio.h>
int main() {
int var = 10;
const int* const p = &var;
printf("Value: %d\n", *p);
return 0;
}
Output
Value: 10
Explanation
The const
keyword is used in C to declare a variable as read-only, i.e., its value cannot be modified. When used with pointers, it can be used to declare a read-only pointer or a pointer that points to a read-only value.
In the above example, the pointer p
is declared as a constant pointer to constant integer. This means that the value of the integer pointed by p
cannot be modified and p
cannot be made to refer to any other integer.
Use
The const
pointer is particularly useful when passing pointers as function arguments, especially when the passed argument is not intended to be modified inside the function. It is also useful in preventing unwanted modification of data through a pointer.
Important Points
- A
const
pointer cannot be made to refer to any other variable once it has been initialized. - The pointed-to value of a
const
pointer cannot be modified, but the pointer itself can be modified. - Syntax for a
const
pointer is the same as a regular pointer, except theconst
keyword is inserted before or after the data type, depending on whether the pointer or the value pointed to is read-only.
Summary
The const
pointer is an important C language feature for declaring pointers that either do not or cannot modify the pointed-to data. By inserting const
before or after the data type in a pointer declaration, one can create either pointers-to-const or const-pointers, depending on whether the value or pointer is read-only. This feature can be particularly useful for passing pointers as function arguments, or in preventing unwanted modification of data through a pointer.