-2

I don't understand the use of the operators & and == in the following piece of code:

Static boolean foo(){

    long stat;
    /* ...code*/

    if (!(stat & 1)){
     /* code... */
    }

     return (stat == SOME_MACRO);
 }
  • What does & do inside the if comparison?
  • What does == do inside the return ?

Thanks in advance.

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132

3 Answers3

3

& is a bitwise AND, which is testing whether the least significant bit of stat is set.

The == makes the function return 1 (meaning "true") if stat is equal the value of to SOME_MACRO. Otherwise it returns 0 (meaning "false").

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • You shouldn't rely on Boolean true being equal to 1. According to the C standard, any non-zero value evaluates as true. Most compilers will generate 1 for true on a Boolean expression, but it is not guaranteed. – brianmearns Sep 05 '13 at 14:03
  • 1
    Any non-zero value evaluates to true, but I think true always evaluates to 1 http://stackoverflow.com/questions/2725044/can-i-assume-booltrue-int1-for-any-c-compiler – Rafi Kamal Sep 05 '13 at 14:07
  • 1
    @sh1ftst0rm: The `==` will only yield 1 or 0 (6.5.9/3). – John Bode Sep 05 '13 at 21:00
  • @JohnBode: Ah ha, nice spotting. I should've known to check the standard first! =) – brianmearns Sep 06 '13 at 00:21
1

if (state & 1) is same is if state is odd.

return (stat == SOME_MACRO); is same as

if (state == SOME_MACRO)
    return true;
else
    return false;

Explanation: The binary representation of any odd number would have a 1 at its last digit. For example,

3 = 11
5 = 101
7 = 111

If you already know what & does, you will notice that when you perform n & 1, all bits except the last one is set to zero, and the last bit remain unchanged. So n & 1 returns the last bit of n, which is 1 if n is odd, and 0 if n is even.

And (state == SOME_MACRO) will evaluate to true if the expression is True, and evaluate to false if the expression is False. So it will return either true or false depending if state is equal to SOME_MACRO or not.

Rafi Kamal
  • 4,522
  • 8
  • 36
  • 50
1

The & (bitwise AND) operator compares each bit of its first operand to the corresponding bit of the second operand. If both bits are 1's, the corresponding bit of the result is set to 1. Otherwise, it sets the corresponding result bit to 0.

the function will return true if stat equal to SOME_MACRO, false otherwise

Flavia Obreja
  • 1,227
  • 7
  • 13