4
\$\begingroup\$

I've been working trying to read some C code and I've found some operators that I don't know:

What's the use of "&=" and "|=" operators when used for microprocessors programming?

\$\endgroup\$
16
\$\begingroup\$

These statements are equivalent:

x = x & 0x01;

x &= 0x01;

It means to perform a bitwise operation with the values on the left and right-hand side, and then assign the result to the variable on the left, so a bit of a short form. If you're not familiar with bitwise operations, I suggest you start getting familiar with those first - the & being a bitwise AND and the | being a bitwise OR.

Hope that helps!

\$\endgroup\$
  • 5
    \$\begingroup\$ "A compound assignment of the form E1 op= E2 differs from the simple assignment expression E1 = E1 op (E2) only in that the lvalue E1 is evaluated only once." \$\endgroup\$ – starblue Jun 3 '11 at 6:38
4
\$\begingroup\$

&= is and equals, |= is or equals. These perform bit-wise operations with the left hand and right hand arguments, and assign the result into the left hand side.

\$\endgroup\$
  • \$\begingroup\$ This definition may look a bit weird for someone unfamilliar with the language. It could be interpreted as "(foo == 0 |= 1)" would be a valid condition. \$\endgroup\$ – JulioC Jun 3 '11 at 4:06
  • \$\begingroup\$ @Júlio Souza - how could you interpret it that way? how would you assign (0|1) into 0? assigning a value into a constant is nonsensical, and should be a strong clue that the construct 0 |= 1 is not valid. \$\endgroup\$ – JustJeff Jun 3 '11 at 10:17
  • \$\begingroup\$ It's a valid interpretation if you say that the = means is equal to (that's what equals means!). == means equals, = means assign ... to. \$\endgroup\$ – stevenvh Jun 3 '11 at 11:18
  • \$\begingroup\$ @Stevenvh - either way, (foo == 0) |= 1 doesn't make any sense, and neither does foo == (0 |= 1) \$\endgroup\$ – JustJeff Jun 3 '11 at 21:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.