What, if anything, is theoretically wrong with this c/c++ statement:
*memory++ = BIT_MASK & *memory;
Where BIT_MASK is an arbitrary bitwise AND mask, and memory is a pointer.
The intent was to read a memory location, AND the value with the mask, store the result at the original location, then finally increment the pointer to point to the next memory location.
You are invoking undefined behaviour because you reference
memorytwice (once for reading, once for writing) in a single statement without an intervening sequence point, and the language standards do not specify when the increment will occur. (You can read the same memory multiple times; the troubles occur when you try to mix some writing in with the reading – as in your example.)You can use:
to achieve what you want to achieve without incurring undefined behaviour.
In the C standard (ISO/IEC 9899:1999 aka C99), §6.5 ‘Expressions’, ¶2 says
That’s the primary source in the C standard. The footnote says:
In addition, ‘Annex C (informative) Sequence Points’ has an extensive discussion of all this.
You would find similar wording in the C++ standard, though I’m not sure it has an analogue to ‘Annex C’.