views:

62

answers:

2

Hi,

What is the answer to "nil%2" in objective-c? I think the answer is 0 but I am not sure.

Thank you.

+4  A: 

It's impossible for a mod-2 operation to return 2—only 0 or 1. I would assume, in this case, that it would be 0.

Noah Witherspoon
`0` is the right answer - but only if you cast `nil` to an integer type first.
Carl Norum
Sorry typo. Thanks for the correction.
David
(int)nil%2 = 0. Thanks.
David
A: 

Actually the answer is a compiler error. nil is a pointer (it is defined as (void *)0), and the only arithmetic operations defined for pointers are addition and subtraction. But if you wanted to know what 0%2 is Noah’s answer is right.

Sven
To be fair, nil is not `(void*)0` it is `(id)0`
jer
Nope. Look at `/usr/include/objc/objc.h`. There `nil` is defined as `__DARWIN_NULL` which in turn is defined in `/usr/include/sys/_types.h` as `((void *)0)` for C code. Also the compiler error says that you can’t use `%` on `void *`.
Sven
@Sven: It is conceptually `(id)0` because not every pointer type is a valid receiver type. For example, `[(void *)0x1234 description]` will show a warning that `void *` is an invalid receiver type, but `[(id)0x1234 description]` does not show this same warning.
dreamlax
True. But `[nil description]` produces the same compiler warning about `void *` being an invalid receiver type.
Sven