views:

128

answers:

5

Hi, I have a method to check weather a number is even or odd:

   -(BOOL)numberIsEven:(unsigned int *)x {


  if (x & 1)
 {
  return TRUE;
 }
 else
{
 return FALSE;
  }
}

however whenever I compile it I get the error:

Invalid operands to binary %

So it's compiling into assembly as a modulus function and failing, somehow, however if I use a modulus based function (arguably slower) I get the same error!

Help me stack overflow

Thanks - Ollie

A: 

That's because (aside from the fact that your code contains numerous typos) x is defined as a pointer. A pointer cannot have modulus performed on it, the result of that is meaningless.

DeadMG
A: 

I suspect you're reading the error message wrong and it really says "Invalid operands to binary &".

The reason it says that is "x" is a pointer, so you need to say:

if (*x & 1)

not

if (x & 1)
David Gelhar
+2  A: 

x is a pointer. The modulo operator will not work on pointers.

return (*x & 1);

This dereferences the pointer, then returns the result of the modulo (implictly cast to a BOOL)

dpoeschl
A: 
return *x & 1;

Since x is a pointer to an int, you need to deference it first.

Alternately, you can change the signature to take an unsigned int. I don't see any advantage to passing a pointer in this situation.

Justin Ardini
A: 
bool isOdd(unsigned int x) {
    return (bool)(x&1);
}

bool isOdd_by_ptr(unsigned int * p) {
    return isOdd( *p );
}

Except that this is actually C, so you don't get anything by casting to bool.

#define IS_ODD( X ) (1 & (X) )

#define IS_ODD_BY_PTR( P ) (1 & *(P) )

Work just fine.

nategoose
Here's something interesting to try: `bool isOdd(int x) { return !isEven(x); }`, `bool isEven(int x) { return !isodd(x); }` =D
NullUserException