Checking if a NSInteger is odd or even
Solution 1:
NSInteger
is defined as int
(or long
on some environments). So checking on oddity is like for plain int:
NSInteger num;
if (num % 2)
// odd
else
// even
Solution 2:
NSInteger n = 5;
NSLog(@"%s", n & 1 ? "odd" : "even");
or using if
if (n & 1) {
; // odd
} else {
; // even
}
with some output:
if (n & 1) {
NSLog(@"odd");
} else {
NSLog(@"even");
}
the pointer example:
NSInteger x = 7;
NSInteger *y = &x;
if (*y & 1) {
NSLog(@"odd");
} else {
NSLog(@"even");
}