Comparison of Pointers and Pointer to Constants

In this tutorial, we will learn how to compare pointers as well as how to use constant variables with them.

Comparison between pointers in C++

In the same way that we can compare any two variables (such as int and double), we can also compare pointers.

And using the same operators:>,>=, <, <=, == and !=

We say, for example, that one pointer is greater than another, when, for example, its memory address in an array points to a variable whose index is greater than another.

For example:
int *ptr1 = array[0];
int *ptr2 = array[1];

So, the comparison: ptr2 > ptr1 will result in a true result.
ptr1 == ptr2 will result in a false result, as they point to different memory addresses.

That is, pointers are variables that store memory addresses.
So, when comparing two pointers, we are comparing two memory addresses, and not the values they point to, ok?

Pointers and C++ const

Whenever we use the keyword const, we are telling the compiler that the value stored in that variable should not be changed.

Often, we want to pass a variable as information for somewhere in code, but we don't want it to be modified in any way, in these cases, it is important to use the keyword const.

So far, we have used non-constant pointers that point to non-constant variables, that is, we can change up to the value of the variable via a pointer that points to it.

You cannot, for example, pass a pointer, which is not constant, to a function that expects a constant variable as an argument. Also, look:
#include <iostream>
using namespace std;

int main()
{
    const double pi = 3.14;
    const double *ptr = &pi;

    cout << *ptr << endl;

    return 0;
}
To point to a constant variable (pi), we had to define a constant pointer (const double *).
Try to remove the 'const' from the pointer declaration, and see what happens.

However, we can have a constant pointer that points to a variable that is not constant:
#include <iostream>
using namespace std;

int main()
{
    double pi = 3.14;
    double * const ptr = &pi;

    cout << *ptr << endl;

    return 0;
}
The difference is that this pointer will ALWAYS point to the same memory address. You can even change the value it points to. But he will never change the address it points to. Constant type pointers must be initialized when they are declared.

Finally, we can have a constant pointer, which points to a constant variable:
#include <iostream>
using namespace std;

int main()
{
    double pi = 3.14;
    const double *const ptr = &pi;

    cout << *ptr << endl;

    return 0;
}
Note that, in this case, we cannot change the address of the pointer (we cannot do ptr =&another_variable) nor can we change the value stored where the pointer points (*ptr = 21.12)

These cases of constant and pointers, as well as the comparison between pointers, are used a lot in the study of strings, for example.

No comments:

Post a Comment