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.
Before we delve into pointers to constants, let's briefly review pointers and constants.
A pointer is a variable that stores the memory address of another variable. It allows us to directly manipulate memory locations in C.
int num = 10;
int *ptr = # // ptr is a pointer to the int variable numA constant in C is a value that cannot be changed during the execution of the program.
const int CONST_NUM = 10; // CONST_NUM is a constant integerNow, 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.
const int *const ptr = &CONST_NUM; // ptr is a constant pointer pointing to the constant integer CONST_NUMIn 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:
#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;
}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! 🌟