-5

I recently saw an open source program where somebody used

if (x & 1){

Where x was an int. I tried this out myself and as far as I can see this has the same effect us using

if (x == 1){

As far as I understand the & symbol is used for referencing objects, but here it seems to be used as an equal to operator.

Am I mistaken in thinking these are the same thing? Or are there different reasons to use each one?

tomh1012
  • 274
  • 1
  • 10
  • 11
    They are not equivalent at all, try with `x = 3` – yassin May 17 '18 at 20:39
  • 1
    `x & 1` is true for any positive odd integer, not just 1. – chepner May 17 '18 at 20:40
  • 2
    `x & 1` is a [bitwise operator](http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_logic_operators). It's the AND operator applied to each bit of `x` with the matching bit of `1`. – François Andrieux May 17 '18 at 20:41
  • 3
    @chepner: And negative odd integers (in two's complement or sign-magnitude representation) or negative even integers (in one's complement) – Ben Voigt May 17 '18 at 20:41
  • @FrançoisAndrieux: *bitwise*, not *size* – Ben Voigt May 17 '18 at 20:42
  • 2
    If `x` is indeed of a native integer type (like `int`) *and* `x` is equal to `1`, then yes `x == 1` and `x & 1` will give the same *result* (but they are not the same). And you should probably take some time to [read a few good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) about the *bitwise operators*. – Some programmer dude May 17 '18 at 20:44
  • 1
    @Someprogrammerdude They'll give you the same result for only certain values, which can be said of many unrelated functions. – François Andrieux May 17 '18 at 20:46
  • `((x & 1) && !(x & ~1))` would give the same result as `(x == 1)` – Yann Droneaud May 17 '18 at 20:50

2 Answers2

7

The statement x & 1 uses the bitwise and operator, in other words, comparing those two values on a binary level, bit by bit. The == comparison is used to test equivalence, in other words, all bits are identical.

What x & 1 does is check that the bit in the 1s place is set to 1. For any unsigned x, any odd value will show up as true since any odd value has that bit set.

Nathan
  • 446
  • 2
  • 15
tadman
  • 208,517
  • 23
  • 234
  • 262
1

The & operator here is the bitwise and. It takes the binary representation of both operands and ands each pair of bits into the result. For example: (assume the following numbers are all binary representations)

10010111 & 00111011

would result in:

00010011

It effectively can be used to "check" to see if a particular set of bits are "set" in an operand since, if they are, the result would be non-zero (i.e. true enough to pass an if statement).

Given that, this code is likely not checking wither x == 1 but rather, whether the first bit of x has been set.

tdk001
  • 1,014
  • 1
  • 9
  • 16