Re: [PATCH v3] git: use ^=1 to toggle between 0 and 1
- From
Junio C Hamano <gitster@pobox.com>
- Date
- Dec 18, 2024, 15:46 UTC
- Message-ID
- <xmqq4j31t2o0.fsf@gitster.g>
- In-Reply-To
- <pull.1620.v3.git.git.1734482536998.gitgitgadget@gmail.com>
"AreaZR via GitGitGadget" <gitgitgadget@gmail.com> writes:
Show 5 quoted lines
> From: Seija Kijin <doremylover123@gmail.com> > > If it is known that an int is either 1 or 0, > doing an exclusive or to switch instead of a > modulus makes more sense and is more efficient.
FWIW, it is much more idiomatic in this codebase to say
foo = !foo;
to flip the polarity of foo when foo is used as a Boolean. It is both more readable than toggling only the bottom bit, and it is much more robust. Here 'used as a Boolean' means 'is it zero, or is it non-zero?', the norm used in the C language.
If the reference to "foo", other than the place where the value of foo is consulted for the sole purpose of fliping between true-false, were to check if it is true or not, i.e.
if (foo) do something; else do something else;
then at this "real" use site, only the zero-ness of the value matters. foo==0 does something different from foo==1, but the code behaves the same way as the case where foo==1, if foo==2 or foo==3.
But the code that flips by
foo = 1 - foo; foo ^= 1;
makes an assumption different from and stricter than the real use site. It only allows foo==0 and foo==1 without a good reason.
But
foo = !foo;
keeps the same assumption as the real use site, which is why we prefer that form.
And like it or not, it is natural to assume that 0 is false and everything else is true when writing in C, and especially in the codebase of this project. So let's not flip
foo = !foo;
into
foo ^= 1;
just to make it look different. Going the other way, or rewriting rewriting modulo 2 arithmetic into !foo form, would be more preferrable.
The "flipped_block" is used like so:
if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS) set MOVED_LINE_ALT bit in flags word;
so it is very much Boolean whose zero-ness matters.