Why does the compiler allow you to "write" a const variable here?

Why are you kind of like a cheat compiler:

const int a = 5;
*((int*)&a)=5;   // VC/armcc does not complain

if above it is the "shorthand" equivalent of this:

const int *ptr2const = &a;
int *ptr = ptr2const;      // as expected error is raised here
*ptr = 5;
+3
source share
7 answers

C-style casts allows you to cast a constant, as in your example. In C ++, you usually use new style styles, such as static_cast<>those that don't allow you to discard a constant. Only const_cast<>allows you to do it.

+7
source

Casting is your way of telling the compiler “I know what I'm doing,” so it doesn't complain. Unfortunately, in this case you will refer to undefined behavior.

+9

,

int *ptr = ptr2const;      // as expected error is raised here

int *ptr = (int *)ptr2const;
+4

C , . . , , , .

+2

, , , const (, ), , .

+2

C, (int*), ++ const_cast , , ( undefined).

int main()
{
    const int x = 1;
    (int&)x = 2;
    std::cout << x << std::endl;
}

1 stdout. .

...

void foo(const int& x)
{
    (int&)x = 2;
}

int main()
{
    int x = 1;
    foo(x);
    std::cout << x << std::endl;
}

2 . , const, foo, , main . , ​​ , const_cast C-, const.

static_cast , .

+1

"", , () ( , ). , undefined.

/ , , const, , .

0

Source: https://habr.com/ru/post/1775312/


All Articles