Can I write a const member from a non-constant structure?

Is this code legal ?:

#include <stdio.h> typedef struct a_d{ int const x; } a_d; int a_d__ctor(a_d *X) { *(int*)&X->x = 42; //<-- legal or not? return 0; } int main() { a_d a; a_d__ctor(&a); printf("ax=%d\n", ax); } 
+1
source share
1 answer

Modifying an object declared with const qualifier causes undefined behavior .

In accordance with the standard (primary focus):

C11 6.7.3 / 6 Type Classifiers

If an attempt is made to modify an object defined using a const-qualified type using an lvalue value with a non-constant-qualifying type , the behavior is undefined.

+3
source

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


All Articles