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?
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.
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.
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.
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.
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With