Note that there are some explanatory texts on larger screens.

plurals
  1. POTest if multiple variable values are either all positive or negative
    text
    copied!<p>Is there a good and fast way in <strong>C/C++</strong> to test if multiple variables contains either all positive or all negative values?</p> <p>Say there a 5 variables to test:</p> <p><strong>Variant 1</strong></p> <pre><code>int test(int a[5]) { if (a[0] &lt; 0 &amp;&amp; a[1] &lt; 0 &amp;&amp; a[2] &lt; 0 &amp;&amp; a[3] &lt; 0 &amp;&amp; a[4] &lt; 0) { return -1; } else if (a[0] &gt; 0 &amp;&amp; a[1] &gt; 0 &amp;&amp; a[2] &gt; 0 &amp;&amp; a[3] &gt; 0 &amp;&amp; a[4] &gt; 0) { return 1; } else { return 0; } } </code></pre> <p><strong>Variant 2</strong></p> <pre><code>int test(int a[5]) { unsigned int mask = 0; mask |= (a[0] &gt;&gt; numeric_limits&lt;int&gt;::digits) &lt;&lt; 1; mask |= (a[1] &gt;&gt; numeric_limits&lt;int&gt;::digits) &lt;&lt; 2; mask |= (a[2] &gt;&gt; numeric_limits&lt;int&gt;::digits) &lt;&lt; 3; mask |= (a[3] &gt;&gt; numeric_limits&lt;int&gt;::digits) &lt;&lt; 4; mask |= (a[4] &gt;&gt; numeric_limits&lt;int&gt;::digits) &lt;&lt; 5; if (mask == 0) { return 1; } else if (mask == (1 &lt;&lt; 5) - 1) { return -1; } else { return 0; } } </code></pre> <p><strong>Variant 2a</strong></p> <pre><code>int test(int a[5]) { unsigned int mask = 0; for (int i = 0; i &lt; 5; i++) { mask &lt;&lt;= 1; mask |= a[i] &gt;&gt; numeric_limits&lt;int&gt;::digits; } if (mask == 0) { return 1; } else if (mask == (1 &lt;&lt; 5) - 1) { return -1; } else { return 0; } } </code></pre> <p>What Version should I prefer? Is there any adavantage using variant 2/2a over 1? Or is there a better/faster/cleaner way?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload