top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What's the PURPOSE of const pointers?

+4 votes
307 views

What's the purpose of const pointers?

posted Jun 2, 2014 by Khusboo

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

There are two topics related with constant and pointer is -
1. constant pointer
2. pointer to a constant

1. Constant Pointers
A constant pointer is a pointer that cannot change the address its holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable.

Sample Declaration: int * const ptr;

2. Pointer to a Constant
A pointer through which cannot change the value of variable it points is known as a pointer to constant. These type of pointers can change the address they point to but cannot change the value at that address.

Sample Declaration: const int* ptr;

Sample Code

int main(void)
{
  {
    int var1 = 0, var2 = 0;
    int *const ptr = &var1;
    ptr = &var2; // Invalid Operation as ptr is a constant pointer
  }
  {
    int var1 = 0;
    const int* ptr = &var1;
    *ptr = 1; // Invalid operation as ptr is pointer to a constant
  }
}

We have a concept of Constant Pointer to a Constant which is mix of two i.e. pointer can not point to another variable neither change the value of the variable it point to.

Sample Declaration: const int* const ptr;

answer Jun 2, 2014 by Salil Agrawal
+1 vote

While writing a program when you are make sure that a pointer is not going to point something else through its life time, better to make it constant so avoid illegal memory access.

answer Jun 2, 2014 by Vimal Kumar Mishra
Similar Questions
+1 vote

Here's a small piece of code:

 static struct {
 const char fmt[10];
 } const x = { "%dn" };
 static const char * const fmt = "%dn";
 printf(fmt, 1);
 printf(x.fmt, 1);

The second printf produces a warning:

 test.c:105:10: warning: format string is not a string literal
[-Wformat-nonliteral]
 printf(x.fmt, 1);
 ^~~~~

From my point of view both format strings are identical. Why can't gcc deduce the format string in the second case?

+1 vote

I wanted to ask what is the GCC C++ equivalent implementation of Windows _ MyFirst and _MyLast vector pointers?

These give direct access to the vectors first and last element, but they are not present in the GCC implementation of the vector class.

0 votes

Does the below code look like valid C++, or is it a G++ bug? 5.2.7 has the dynamic_cast operator shall not cast away constness (5.2.11).

The other compilers I could check quickly (clang, icc, msvc) all reject the code, GCCs 3.3, 4.6, 4.7 and 4.8 accept the code.

class A {
};

class B : public A {
};

int main() {
 A* a;
 B* b = new B();
 a = dynamic_cast(b);
 return 0;
}
...