Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant value changing

Suppose I have a struct definition:

struct thing
{
    thing* x;
    int z;

    thing() : x(this), z(0) {}
    void foo() const
    {
        this->x->z++;
    }
};

Note that I create a mutable pointer to myself (evil laugh)

And then I can use this later like this:

int main()
{
    const thing c;
    c.foo();
    assert(c.z == 1);
    c.foo();
    assert(c.z == 2);
    return c.z;
}

And as you can see it seems that I can change a constant value......is this UB?

like image 979
DarthRubik Avatar asked Oct 08 '18 21:10

DarthRubik


People also ask

Can a constants value change?

A constant is a data item whose value cannot change during the program's execution. Thus, as its name implies – the value is constant. A variable is a data item whose value can change during the program's execution. Thus, as its name implies – the value can vary.

How do you change a const value?

Changing Value of a const variable through pointerBy assigning the address of the variable to a non-constant pointer, We are casting a constant variable to a non-constant pointer. The compiler will give warning while typecasting and will discard the const qualifier.

Can const object change?

The property of a const object can be change but it cannot be change to reference to the new object. The values inside the const array can be change, it can add new items to const arrays but it cannot reference to a new array. Re-declaring of a const variable inside different block scope is allowed.

How do you define a constant value?

Constant value is a fixed value. In Algebra, a constant is a number, or sometimes it is denoted by a letter such as a, b or c for a fixed number. For example x+2=10, here 2 and 10 are constants.


1 Answers

[dcl.type.cv]p4:

Except that any class member declared mutable ([dcl.stc]) can be modified, any attempt to modify ([expr.ass], [expr.post.incr], [expr.pre.incr]) a const object ([basic.type.qualifier]) during its lifetime ([basic.life]) results in undefined behavior.

[basic.type.qualifier]p1:

A const object is an object of type const T or a non-mutable subobject of such an object.

c.z is a const object, because it is a non-mutable subobject of c. Your code attempts to modify it during its lifetime. It follows that the code has undefined behavior.

like image 124
T.C. Avatar answered Nov 19 '22 19:11

T.C.