C Pointer to Constant 🎯

beginner
25 min

C Pointer to Constant 🎯

Welcome to another exciting lesson at CodeYourCraft! Today, we're diving into the fascinating world of C Programming, focusing on a crucial concept - Pointers to Constants. By the end of this lesson, you'll be able to master this topic and apply it to your coding projects.

What are Pointers and Constants in C? 📝

Before we delve into pointers to constants, let's briefly review pointers and constants.

Pointers

A pointer is a variable that stores the memory address of another variable. It allows us to directly manipulate memory locations in C.

c
int num = 10; int *ptr = # // ptr is a pointer to the int variable num

Constants

A constant in C is a value that cannot be changed during the execution of the program.

c
const int CONST_NUM = 10; // CONST_NUM is a constant integer

Pointers to Constants 💡

Now, let's learn about pointers to constants. A pointer to a constant is a pointer that points to a constant variable, but we cannot change the value it points to.

c
const int *const ptr = &CONST_NUM; // ptr is a constant pointer pointing to the constant integer CONST_NUM

In this example, ptr is a constant pointer that points to the constant integer CONST_NUM. We cannot change the value of ptr, nor can we change the value of CONST_NUM.

Here's a practical example:

c
#include <stdio.h> int main() { const int CONST_NUM = 10; const int *const ptr = &CONST_NUM; printf("The value of CONST_NUM: %d\n", CONST_NUM); printf("The address of CONST_NUM: %p\n", &CONST_NUM); printf("The value pointed by ptr: %d\n", *ptr); printf("The address pointed by ptr: %p\n", ptr); // Invalid assignment: cannot assign to const 'CONST_NUM' // *ptr = 20; // Invalid assignment: cannot change the value of ptr // ptr = &another_num; return 0; }
Quick Quiz
Question 1 of 1

What is the output of the following code?

By understanding pointers to constants, you've gained another essential skill in C programming. Keep practicing and explore more concepts at CodeYourCraft! 🌟