0

Is the compound operator '&=' logical or bitwise AND ?

In other words, is a &= b the same as:

  • a = a & b
  • a = a && b
niton
  • 8,771
  • 21
  • 32
  • 52
Zyyk Savvins
  • 483
  • 4
  • 8
  • 14
  • 5
    Why don't you run a sample and see for yourself? -1 – axiom Nov 29 '12 at 14:53
  • Fair enough (+1 to comment above), but he may not have a build environment ready to go ATM. This seems a fair question to me. – Cloud Nov 29 '12 at 15:07
  • 1
    Ok, But we have http://ideone.com/ ,http://codepad.org/ to name a few. – axiom Nov 29 '12 at 15:13
  • @axoim I was away from home, and didn't have access to a computer with an environment. school computers, ya know ... I tried it out now, seems to work like &&, but its weird coz when I googled it, it says its bitwise – Zyyk Savvins Nov 29 '12 at 17:01

5 Answers5

2

It's the bitwise AND, not the logical. (have to add some characters)

effeffe
  • 2,821
  • 3
  • 21
  • 44
2

a &= b is using the bitwise AND operator. Think of the += operation:

a += 5;

is the same as:

a = a + 5;

It's just a combination of two operations: & and =.

Mike
  • 47,263
  • 29
  • 113
  • 177
  • @effeffe - My point was just `&=` and `+=` are two operations put together, so why would the OP think `&=` should end up `= &&` anymore then `+=` would end up `++` – Mike Nov 29 '12 at 15:00
  • Because there is no binary operator `++`, while both `&` and `&&` exist and they are both binary operators. – effeffe Nov 29 '12 at 15:04
2

In C, a &= b is a = a & b, i.e. bitwise. In C++, where there is a dedicated bool type, &= on booleans is boolean as well, as is a simple & on bool. None of these does exhibit the short-circuit behaviour of &&, though.

MvG
  • 57,380
  • 22
  • 148
  • 276
2

It's bitwise ANDsimple

When you do a&=b It means a=a&b

Remember aand bshould be integral typeor promoted to integer type

While && is logical AND.

Omkant
  • 9,018
  • 8
  • 39
  • 59
2

This is one of the queries that can be resolved through experimentation rather than interrogation:

#include <stdio.h>
#include <inttypes.h>

int main(int argc, char *argv[]) {
    uint8_t a = 0xFF;
    uint8_t b = 0x0F;

    a &= b;
    printf("a &= b : %02X\n",a);

    a = 0xFF;
    printf("a & b : %02X\n", a & b);
    printf("a && b: %02X\n", a && b);
}

Prints:

a &= b : 0F
a & b : 0F
a && b: 01

to the console.

FluffulousChimp
  • 9,157
  • 3
  • 35
  • 42
  • 2
    Actually, it's best resolved by consulting an authoritative C reference manual, or checking the [standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf). There are times where experimentation is the *wrong* approach (anything that invokes undefined behavior like `i = i++`, for example). – John Bode Nov 29 '12 at 15:12
  • True - although adult learning theory would suggest an important role for learning _through_ experimentation. In this case, reading the standard would seem the most prudent as you suggest. – FluffulousChimp Nov 29 '12 at 15:21