5

I ran into this bit of code today:

indexValid &= x >= 0;

What does the &= mean? Could someone explain what is occurring in this statement?

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
guy8214
  • 1,115
  • 2
  • 12
  • 14

2 Answers2

9

This is not about Objective-C, but regular C.

Here the statement with the &= operator is equivalent to indexValid = indexValid & (x >= 0). The & operator itself is called the bitwise and operator, and ANDs the operands. Which means, returns 1 only if both operands are 1, else returns 0 if any of the operands is not 1. ANDing and ORing is commonly used in setting flags in software.

For example, if indexValid is 0011010 in binary and you AND it with (x >= 0) (which is a boolean expression result, either 1 or 0), the result is 0000000 and (let's say x >= 0 evaluates to 1) as 0011010 & 0000001 evaluates to 0000000.

If you don't know about binary logic, http://en.wikipedia.org/wiki/Boolean_logic is a good source to start.

Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389
2

It is the bitwise AND plus assignment operator (or 'and accumulate').

It combines a bitwise AND against the left-hand operand with assignment to said operand.

x&= y;

is

x= x & y; 
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49