Modifying a const variable using a pointer
suggest changeint main (void) { const int foo_readonly = 10; int *foo_ptr; foo_ptr = (int *)&foo_readonly; /* (1) This casts away the const qualifier */ *foo_ptr = 20; /* This is undefined behavior */ return 0; }
Quoting ISO/IEC 9899:201x, section 6.7.3 §2:
If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined. […]
- In GCC this can throw the following warning:
warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents