tags:

views:

118

answers:

4

Hello. I was writing a function which checks if every digit in a number is odd. I came accross this weird behaviour. Why does the second function return different (incorrect) results, eventhough its basically the same? (implemented in an opposite way)

#include <stdio.h>

int all_odd_1(int n) {
 if (n == 0) return 0;
 if (n < 0) n = -n;

 while (n > 0) {
  if (n&1 == 1)
     n /= 10;
  else
     return 0;
  }

return 1;
}


int all_odd_2(int n) {
 if (n == 0) return 0;
 if (n < 0) n = -n;

 while (n > 0) {
  if (n&1 == 0)
     return 0;
  else
     n /= 10;
  }

return 1;
}


int main() {

 printf("all_odd_1\n");
 printf("%d\n", all_odd_1(-131));
 printf("%d\n", all_odd_1(121));
 printf("%d\n", all_odd_1(2242));
 printf("-----------------\n");
 printf("all_odd_2\n");
 printf("%d\n", all_odd_2(131));
 printf("%d\n", all_odd_2(121));
 printf("%d\n", all_odd_2(2242));
 return 0;
}
+10  A: 
warning: suggest parentheses around comparison in operand of '&'

Well, how about adding them ? Change n&1 to (n&1). Always ask for warnings.

nc3b
I did not get any warnings, nor I am able to set them. Which compiler are you using. What kind of options are you passing to it?
tryt
I can't say for sure which compiler nc3b is using, but `gcc -Wall` gives the verbatim warning. http://gcc.gnu.org/
msw
Yes, I use gcc. I didn't just mention `use gcc -Wall` because the OP didn't mention his compiler.
nc3b
+5  A: 

The == operator has higher precedence than the & operator, so your if (n&1 == 0) statement is not doing what you expect!

(and the if (n&1 == 1) statement works only by coincidence that 1 == 1 evaluates to 1 ;)

Autopulated
+2  A: 

Operator precedence. n & 1 == 0 is equivalent to n & (1 == 0)

msw
+2  A: 

It is a problem related to the order of execution. Try to use if ((n&1) == 0) in all_odd_2 and everything will work.

Maurizio Reginelli