Checking every digit in the quantity for oddness

I wrote a function that checks if every digit is in a number. I came to this strange behavior. Why does the second function return different (incorrect) results, although basically it's the same thing? (implemented in reverse)

#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; } 
+4
source share
4 answers

The == operator takes precedence over the & operator, so your if (n&1 == 0) operator does not do what you expect!

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

+5
source
 warning: suggest parentheses around comparison in operand of '&' 

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

+10
source

Operator Priority. n & 1 == 0 equivalent to n & (1 == 0)

+2
source

This is a run-time issue. Try using if ((n & 1) == 0) in all_odd_2 and everything will work.

+2
source

Source: https://habr.com/ru/post/1310903/


All Articles