Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer evenness testing (% 2 vs & 1)

Tags:

c

Do these two statements compile equivalently: n % 2 == 0 and n & 1 == 0 ?

if not, is one more efficient?

like image 296
tks Avatar asked Oct 19 '25 05:10

tks


2 Answers

No, they do not always give the same result. The C standard allows for ones' complement implementations, in which case they will give a different result for negative n.

like image 175
caf Avatar answered Oct 21 '25 19:10

caf


A similar question was asked yesterday.

i % 2 and i & 1 are not the same:

  • If your integer is not unsigned, depending on its representation, n & 1 does not necessarily indicate whether your integer is even or odd.
  • i % 2 can be negative.

For unsigned integers, a good compiler should reasonably produce equally efficient code.

like image 35
Benoit Avatar answered Oct 21 '25 19:10

Benoit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!