C Constant Pointer to Constant šŸŽÆ

beginner
12 min

C Constant Pointer to Constant šŸŽÆ

Welcome to our deep dive into C's const pointer to const concept! By the end of this lesson, you'll have a solid understanding of this essential topic. Let's get started!

Understanding const and Pointers šŸ“

Before diving into const pointers to const, let's quickly review the basics of const and pointers in C.

const

In C, you can declare a variable as const to indicate that its value is constant and should not be changed during the program's execution.

c
const int my_constant = 42;

Pointers

A pointer is a variable that stores the memory address of another variable. You can declare a pointer by adding an asterisk (*) before the variable name.

c
int my_variable = 21; int* my_pointer; my_pointer = &my_variable;

const Pointers šŸ’”

Now that we've covered const and pointers, it's time to discuss const pointers. A const pointer is a pointer that points to a const variable.

c
int my_constant = 42; const int* my_const_pointer = &my_constant;

šŸ’” Pro Tip: When you initialize a const pointer, it points to a const variable. However, once the pointer has been initialized, you can change what it points to, but you cannot modify the value it points to.

Pointers to const šŸ“

On the other hand, a pointer to const is a pointer that points to a non-const variable, but the value it points to is const.

c
int my_variable = 21; const int* my_pointer_to_const = &my_variable;

šŸ’” Pro Tip: You can modify the value that a pointer to const points to, but once it points to a const variable, you cannot change the value.

Examples šŸŽÆ

Now, let's look at some examples to illustrate the difference between const pointers and pointers to const.

const Pointer Example

c
#include <stdio.h> int main() { const int my_constant = 42; const int* my_const_pointer = &my_constant; printf("my_constant: %d\n", my_constant); printf("my_const_pointer: %p\n", my_const_pointer); my_const_pointer = &my_variable; // Compile error! my_const_pointer points to a non-const variable. *my_const_pointer = 21; // Compile error! You cannot modify the value a const pointer points to. return 0; } int my_variable = 21;

Pointer to const Example

c
#include <stdio.h> int main() { int my_variable = 21; const int* my_pointer_to_const = &my_variable; printf("my_variable: %d\n", my_variable); printf("my_pointer_to_const: %p\n", my_pointer_to_const); my_pointer_to_const = &my_constant; // This is allowed *my_pointer_to_const = 42; // Compile error! You cannot modify the value a pointer to `const` points to. return 0; } const int my_constant = 42;

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What happens when you try to modify the value a `const` pointer points to?

Wrapping Up āœ…

Now you have a good understanding of const pointers to const in C. By using const pointers and pointers to const, you can create more robust and secure programs. Happy coding! šŸ’»šŸŽ‰