Checking if two numbers have the same sign Is there a more elegant way than the following to check if two numbers have the same sign?

 bool sameSign(int num1, int num2)
    {
        if (num1 &gt; 0 &amp;&amp; num2 &lt; 0)
            return false;
        if (num1 &lt; 0 &amp;&amp; num2 &gt; 0)
            return false;
        return true;
    }


It could also be written as the not case of all of this (e.g. check the true cases and return false at the end).

By design, the two integers will never contain a zero value.
First up, your code has bugs. What if one of the numbers is 0? 0 should be positive, but your code treats it as negative in some tests, and positive in others. When comparing against 0 you should use &gt;=, not just &gt;.

The actual code is quite readable, though, and the performance is probably not horrible. I would recommend a single return statement though. A single return statement is easier if you check for "the same sign", and not "opposite signs". 

Take your code:


bool sameSign(int num1, int num2)
{
    if (num1 &gt; 0 &amp;&amp; num2 &lt; 0)
        return false;
    if (num1 &lt; 0 &amp;&amp; num2 &gt; 0)
        return false;
    return true;
}



Fix the 0-handling, and you have:

bool sameSign(int num1, int num2)
{
    return num1 &gt;= 0 &amp;&amp; num2 &gt;= 0 || num1 &lt; 0 &amp;&amp; num2 &lt; 0
}


Now, that's pretty good, and I would happily "pass" that in a code review, but, can you do some tricks?

The simplest (code wise) is to use XOR:

return (num1 ^ num2) &gt;= 0


That compares the bits, and if they are the same, it sets the resulting bit to 0. If the sign bits are the same, the resulting sign-bit is 0, and thus a positive (or 0) value.