What is indirection in c++?

28 Dec 2022 Balmiki Mandal 0 C++

Understanding Indirection in Programming

Indirection is a programming concept that refers to the ability to indirectly access a value or memory location by using a pointer or a reference instead of directly accessing it. In other words, instead of working with the value or memory location itself, the programmer works with a reference or a pointer that points to the location of the value or memory in the computer's memory.

C++ that demonstrates the concept of indirection using pointers:

#include 

int main() {
    int x = 10;
    int* ptr = &x;

    std::cout << "The value of x is: " << x << std::endl;
    std::cout << "The value of ptr is: " << ptr << std::endl;
    std::cout << "The value of *ptr is: " << *ptr << std::endl;

    *ptr = 20;

    std::cout << "The value of x is now: " << x << std::endl;
    std::cout << "The value of *ptr is now: " << *ptr << std::endl;

    return 0;
}

In this program, we declare an integer variable x and initialize it with the value 10. We also declare a pointer variable ptr of type int*, which is assigned the address of x using the address-of operator &.

We then use the dereference operator * to access the value stored at the memory location pointed to by ptr. This is an example of indirection, as we are indirectly accessing the value of x through the pointer ptr.

We then assign the value 20 to *ptr, which changes the value of x as well, since ptr points to the same memory location as x.

The output of the program will be:

The value of x is: 10
The value of ptr is: 0x7fff5a5b5a5c
The value of *ptr is: 10
The value of x is now: 20
The value of *ptr is now: 20

This program demonstrates how indirection can be used to access and manipulate data indirectly through pointers in C++.

Further Reading:

For further information and examples, Please visit[ course in production]

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.