Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

For below snippet,

#include <iostream>
using namespace std;

void fun(const int *p)
{
    int *q = const_cast<int *>(p);
    *q = *q * 10;
    cout<<"q: "<<q<<" Value: "<<*q<<endl;
}

int main()
{
    const int a = 10;
    const int *z = &a;
    fun(z);
    cout<<"z: "<<z<<""<<"Address of a: "<<&a<<endl;
    cout<<"value at z: "<<*z<<" value in a: "<<a<<endl;
}

the output produced is

q: 0x7fff65910fcc    Value: 100
z: 0x7fff65910fcc   Address of a: 0x7fff65910fcc
value at z: 100      value in a: 10

Why the value of a is not modified even though i tried to modify it in fun()?

How come the address of a and the pointer z are same but the values are different?

Is it some kind of undefined behavior with const_cast ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

Is it some kind of undefined behavior with const_cast ?

Yes, your program contains undefined behavior.

This means that you cannot have any expectation on its output. The reason is given by paragraph 7.1.6.1/4 of the C++11 Standard:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior

Paragraph 5.2.11/7 on const_cast contains a further warning:

[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior (7.1.6.1). —end note ]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...