shellwhale
shellwhale

Reputation: 902

How to return 1 if both number share sign without if statements?

Let's say I have two variables.

int a = -10;
int b = 10;

How can I return 0 if they have different sign or 1 if they have same signs ? Again without if statements

Upvotes: 1

Views: 185

Answers (5)

P.W
P.W

Reputation: 26800

int msb = 1u << (sizeof(int) * CHAR_BIT  - 1);
return !((msb & a) ^ (msb & b));

Upvotes: 2

Gerhardh
Gerhardh

Reputation: 12404

As the question is probably only theoretically relevant (homework?), I will ignore the correct handling of value 0. You would need to define if it is positive, negative or both.

1.

return (a>=0) == (b>=0);

2.

return ((double)a*b) > 0;
return ((double)a/b) > 0;

(Convert to double to avoid overflow.) Warning: Division by zero might occur.

Upvotes: 5

heracho
heracho

Reputation: 610

Here's an algebraic solution. Just if you are sure that neither a or b is 0.

return abs(a/abs(a) + b/abs(b))/2;

Upvotes: 1

Lundin
Lundin

Reputation: 214495

The obscure but probably quite effective version would be this:

#include <limits.h>

return !((a & INT_MIN) ^ (b & INT_MIN));

Explanation:

No matter signed representation on the given system, the MSB of the variable will always hold a sign bit. By checking if the sign bit is set on each variable, we can see if it is signed or not.

This is done by bitwise masking, for example a & 0x80000000 on a 32 bit system. This returns 0x80000000 if the number is signed, otherwise 0.

The portable version of the 0x80... mask is INT_MIN from limits.h.
(Or if you will, you can use 1u << (CHAR_BIT*sizeof(int))).

You want to return 1 if the variables have the same sign, otherwise 0. That is logical XNOR. C does not have that operator but we can create it through !(a ^ b), read as "NOT (a XOR b)".

And so we end up with the above expression. For those who doesn't know the difference in operator precedence between bitwise AND and bitwise XOR (gasp, shame on you!), I added the inner parenthesis, although you can also drop them if you wish to pose with your C operator precedence knowledge:

return !( a & INT_MIN ^ b & INT_MIN );

Upvotes: 2

ColdIV
ColdIV

Reputation: 1104

Like this?

return ((a >= 0 && b >= 0) || (a < 0 && b < 0));

Upvotes: 9

Related Questions