-1

I've got an argument with my co-workers. Once I did try to modify constant reference.

Sample of code is below:

#include <cstdio>
#include <cstdlib>

using namespace std;

int main(int argc, char const *argv[])
{
   const int* A = NULL;

   printf("A = %p\n", A);

   int** pA = const_cast<int**>(&A);

   *pA = new int(5);

   if (pA != NULL)
      printf("pA = %p, value = %d\n", pA, *pA);
   else
      printf("pA null pointer\n");

   if (A != NULL)
      printf("A = %p, value = %d\n", A, *A);
   else
      printf("A null pointer\n");

   return 0;
}

Everything works fine and the log is

 A = 00000000
 pA = 0028FED8, value = 4068760
 A = 003E1598, value = 5

I think it works that way:

  1. I create a const pointer variable A with '0' (zero) value is stack. It is local variable wich occupies 4 bytes of memory in stack.

  2. then I create a pointer to pointer variable, I cast away constant modification and take address of the variable

I think this code works fine and will not lead to a bug. But I need some kind of explanations. Am I right?

theroom101
  • 599
  • 1
  • 9
  • 23

1 Answers1

3

const int *a and int * const a are different.

Case 1

[const is used on *a]

Here the value of a is constant. The address pointed by a can be changed.

const int *a = malloc(sizeof (int));
if (a)
{
  //*a = 10;                    //not allowed
  a = malloc(sizeof (int));;   //allowed
}

Case 2

[const is used on a]

Here the address of a is constant. The value of a can be changed.

int * const a = malloc(sizeof (int));
if (a)
{
  *a = 10;                      //allowed
  //a = malloc(sizeof (int));;    //not allowed
}

EDIT:

As suggested by @lifeOfPI, read about using const_cast .

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • would be a perfect answer if it explains `const_cast<>` and possible resulting undefined behaviors as it was used in sample code, anyway +1 – lifeOfPI Sep 09 '14 at 12:24