I want to iterate over integers up to some power of 2 t by skipping all integers having a specific bit set. Let m be some power of 2 (smaller than t), I want to skip all integers j such that j&m != 0. I like the following for-loop, but I wonder whether it is perfectly defined according to the standard:
for (int j=0; j < t; j += (++j) & m) {
...
}
The idea is:
- increment
jwith++jfor iterating over all integers - whenever the previous increment sets the bit of weight
m, add alsomfor skipping the whole block.
But since there are two increments in the same expression I want to make sure it is perfectly correct.
The behaviour of this program is not defined (UB) as
*(thank you Eric)*there is no sequence point between themodification and assignment are not sequenced.Many compilers will emit a warning:
Even if it was OK I would strongly discourage you from writing this kind of "hacky" expressions as they are very difficult to read for humans making the code very hard to understand, debug and maintain