Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to a const int in c++

Tags:

c++

pointers

While I was learning about const variables in c++, I tried this :

#include <iostream>

int main()
{
    const int p = 20;

    int* a = const_cast<int*>(&p);

    *a = 10;

    std::cout<<"Value at a: "<<(*a)<<std::endl;
    std::cout<<"Value of p: "<<p<<std::endl;

    std::cout<<"Their addresses : "<<std::endl;
    std::cout<<a<<" "<<&p<<std::endl;
    return 0;
}

and it produces the output:

Value at a: 10
Value of p: 20
Their addresses : 
0x7fff4646d7d4 0x7fff4646d7d4

Seemingly I assigned the value 10 to the memory address of p, but their values come out different. Why is it so?

like image 253
nradk Avatar asked Feb 02 '14 10:02

nradk


People also ask

Can a pointer point to a const?

C++ Constant Pointers to constants: In the constant pointers to constants, the data pointed to by the pointer is constant and cannot be changed. The pointer itself is constant and cannot change and point somewhere else.

How do you declare a pointer to an integer constant?

We declare a pointer to constant. First, we assign the address of variable 'a' to the pointer 'ptr'. Then, we assign the address of variable 'b' to the pointer 'ptr'. Lastly, we try to print the value of 'ptr'.

What is const int * in C?

int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn't be changed.

Can we use const int in C?

int const *ptr; We can change the pointer to point to any other integer variable, but cannot change the value of the object (entity) pointed using pointer ptr. The pointer is stored in the read-write area (stack in the present case).


1 Answers

Attempting to modify an object that was originally declared const gives you undefined behaviour.

§7.1.6.1/4 [dcl.type.cv] Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior.

Chances are, your compiler is replacing all occurences of p in your code with the value 20, since you have promised that it will not change. So the line that prints p has changed to:

std::cout<<"Value of p: "<<20<<std::endl;

So it prints 20 regardless of whether you modified the original object. Of course, since you have undefined behaviour, this kind of reasoning is fruitless and you should not invoke undefined behaviour in your program.

like image 121
Joseph Mansfield Avatar answered Oct 12 '22 23:10

Joseph Mansfield