Approved way to avoid lvalue cast warnings and errors?

This is related to JoGusto’s answer at Casting Error: lvalue required as left operand of assignment. In the answer, he/she states:

but there is one case where it is not true: casting, then dereferencing a pointer:

*((int *) chrPtrValue) = some_integer_expression;

I think I found the answer at Joseph Mansfield answer from Why does an lvalue cast work?, where he cited the standard. But that confused me more because I can differentiate between lvalues and rvalues, but xvalues and prvalues are still new to me.

Naively, it seems to me that the rule is present for a reason, so some of the methods for circumventing it would probably be [indirectly or directly] illegal also.

I have a few questions related to the lvalue cast. The use cases includ the following. In the first case, the underlying types are different. In the second case, the qualifiers were changed.

float f;
*(static_cast<int*>(&f)) = 1;

int ptr = ...;
*(static_cast<volatile int*>(&ptr)) = NULL; 

Is it legal C and C++ circumvent the lvalue cast error using indirection then dereferencing?

If the cast only changes the qualifiers (i.e., static const or volatile) , then is it still legal in C and C++?

If its legal C and C++, then does it violate other rules, like GCC’s aliasing rules?

Finally, if it does violate C or C++, or other rules, then what is the approved way to do it (perhaps a memcpy or memmove)?

Source: gcc

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.