3 ms·
Yes, you are correct, it is UB. Try this code: void foo(const int * const p) { *(int*)p = 3; // UB? So sue me! } It compiles with g++ and
by WalterBright 4y ago
Yes, you are correct, it is UB. Try this code:
void foo(const int * const p)
{
*(int*)p = 3; // UB? So sue me!
}
It compiles with g++ and clang++ with no warnings or errors. gcc and clang, too. Sure, it's UB, but the compiler won't even warn you.
I.e. it serves no purpose, other than documentation. Let's try it in D:
@safe
void foo(const int *p)
{
*cast(int*)p = 3;
}
Error: cast from const(int*) to int* not allowed in safe code
- maccard 4y agoI think we're in agreement here, but speaking past each other! Your snippet isn't actually UB though, it's perfectly fine. See [0] > I.e. it serves no purpose, other than documentation Yeah, agreed. [0] https://gcc.godbolt.org/z/v4qYME8fP https://gcc.godbolt.org/z/v4qYME8fP