Would you use num%2 or num&1 to check if a number is even?

后端 未结 12 2832
南旧
南旧 2020-12-18 19:19

Well, there are at least two low-level ways of determining whether a given number is even or not:

 1. if (num%2 == 0) { /* even */ } 
 2. if ((num&1) ==          


        
12条回答
  •  眼角桃花
    2020-12-18 19:24

    At this point, I may be just adding to the noise, but as far as readability goes, the modulo option makes more sense. If your code is not readable, it's practically useless.

    Also, unless this is code to be run on a system that's really strapped for resources (I'm thinking microcontroller), don't try to optimize for the compiler's optimizer.

提交回复
热议问题