<p>Is there any reason not to use the bitwise operators &amp;, |, and ^ for "bool" values in C++? </p>

<p>I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use &amp; and |. I also need to accumulate Boolean values sometimes, and &amp;= and |= can be quite useful.</p>

<p>I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this?</p>

[{'answer_id': 24552, 'author': 'kokos', 'author_id': 1065, 'author_profile': 'https://Stackoverflow.com/users/1065', 'pm_score': 4, 'selected': False, 'text': "<p>The raised eyebrows should tell you enough to stop doing it. You don't write the code for the compiler, you write it for your fellow programmers first and then for the compiler. Even if the compilers work, surprising other people is not what you want - bitwise operators are for bit operations not for bools.<br>\nI suppose you also eat apples with a fork? It works but it surprises people so it's better not to do it.</p>\n"}, {'answer_id': 24560, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 7, 'selected': True, 'text': "<p><code>||</code> and <code>&amp;&amp;</code> are boolean operators and the built-in ones are guaranteed to return either <code>true</code> or <code>false</code>. Nothing else.</p>\n\n<p><code>|</code>, <code>&amp;</code> and <code>^</code> are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 &ndash; as is the case with the C language &ndash; you may end up with some behavior you didn't want. For instance:</p>\n\n<pre><code>BOOL two = 2;\nBOOL one = 1;\nBOOL and = two &amp; one;   //and = 0\nBOOL cand = two &amp;&amp; one; //cand = 1\n</code></pre>\n\n<p>In C++, however, the <code>bool</code> type is guaranteed to be only either a <code>true</code> or a <code>false</code> (which convert implicitly to respectively <code>1</code> and <code>0</code>), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say <code>b = b &amp;&amp; x</code> and be done with it.</p>\n"}, {'answer_id': 25220, 'author': 'genix', 'author_id': 2714, 'author_profile': 'https://Stackoverflow.com/users/2714', 'pm_score': 2, 'selected': False, 'text': "<p>Patrick made good points, and I'm not going to repeat them. However might I suggest reducing 'if' statements to readable english wherever possible by using well-named boolean vars.For example, and this is using boolean operators but you could equally use bitwise and name the bools appropriately:</p>\n\n<pre><code>bool onlyAIsTrue = (a &amp;&amp; !b); // you could use bitwise XOR here\nbool onlyBIsTrue = (b &amp;&amp; !a); // and not need this second line\nif (onlyAIsTrue || onlyBIsTrue)\n{\n .. stuff ..\n}\n</code></pre>\n\n<p>You might think that using a boolean seems unnecessary, but it helps with two main things:</p>\n\n<ul>\n<li>Your code is easier to understand because the intermediate boolean for the 'if' condition makes the intention of the condition more explicit.</li>\n<li>If you are using non-standard or unexpected code, such as bitwise operators on boolean values, people can much more easily see why you've done this.</li>\n</ul>\n\n<p>EDIT: You didnt explicitly say you wanted the conditionals for 'if' statements (although this seems most likely), that was my assumption. But my suggestion of an intermediate boolean value still stands.</p>\n"}, {'answer_id': 33801, 'author': 'Mark Borgerding', 'author_id': 3343, 'author_profile': 'https://Stackoverflow.com/users/3343', 'pm_score': 4, 'selected': False, 'text': '<p>I think </p>\n\n<pre><code>a != b\n</code></pre>\n\n<p>is what you want</p>\n'}, {'answer_id': 33820, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 0, 'selected': False, 'text': '<p>IIRC, many C++ compilers will warn when attempting to cast the result of a bitwise operation as a bool.  You would have to use a type cast to make the compiler happy.</p>\n\n<p>Using a bitwise operation in an if expression would serve the same criticism, though perhaps not by the compiler.  Any non-zero value is considered true, so something like "if (7 &amp; 3)" will be true.  This behavior may be acceptable in Perl, but C/C++ are very explicit languages.  I think the Spock eyebrow is due diligence. :)  I would append "== 0" or "!= 0" to make it perfectly clear what your objective was.</p>\n\n<p>But anyway, it sounds like a personal preference.  I would run the code through lint or similar tool and see if it also thinks it\'s an unwise strategy.  Personally, it reads like a coding mistake.</p>\n'}, {'answer_id': 33995, 'author': 'Patrick Johnmeyer', 'author_id': 363, 'author_profile': 'https://Stackoverflow.com/users/363', 'pm_score': 5, 'selected': False, 'text': "<p>Two main reasons.  In short, consider carefully; there could be a good reason for it, but if there is be VERY explicit in your comments because it can be brittle and, as you say yourself, people aren't generally used to seeing code like this.</p>\n\n<h2>Bitwise xor != Logical xor (except for 0 and 1)</h2>\n\n<p>Firstly, if you are operating on values other than <code>false</code> and <code>true</code> (or <code>0</code> and <code>1</code>, as integers), the <code>^</code> operator can introduce behavior not equivalent to a logical xor.  For example:</p>\n\n<pre><code>int one = 1;\nint two = 2;\n\n// bitwise xor\nif (one ^ two)\n{\n  // executes because expression = 3 and any non-zero integer evaluates to true\n}\n\n// logical xor; more correctly would be coded as\n//   if (bool(one) != bool(two))\n// but spelled out to be explicit in the context of the problem\nif ((one &amp;&amp; !two) || (!one &amp;&amp; two))\n{\n  // does not execute b/c expression = ((true &amp;&amp; false) || (false &amp;&amp; true))\n  // which evaluates to false\n}\n</code></pre>\n\n<p>Credit to user @Patrick for expressing this first.</p>\n\n<h2>Order of operations</h2>\n\n<p>Second, <code>|</code>, <code>&amp;</code>, and <code>^</code>, as bitwise operators, do not short-circuit.  In addition, multiple bitwise operators chained together in a single statement -- even with explicit parentheses -- can be reordered by optimizing compilers, because all 3 operations are normally commutative.  This is important if the order of the operations matters.</p>\n\n<p>In other words</p>\n\n<pre><code>bool result = true;\nresult = result &amp;&amp; a() &amp;&amp; b();\n// will not call a() if result false, will not call b() if result or a() false\n</code></pre>\n\n<p>will not always give the same result (or end state) as</p>\n\n<pre><code>bool result = true;\nresult &amp;= (a() &amp; b());\n// a() and b() both will be called, but not necessarily in that order in an\n// optimizing compiler\n</code></pre>\n\n<p>This is especially important because you may not control methods <code>a()</code> and <code>b()</code>, or somebody else may come along and change them later not understanding the dependency, and cause a nasty (and often release-build only) bug.</p>\n"}, {'answer_id': 69680, 'author': 'bk1e', 'author_id': 8090, 'author_profile': 'https://Stackoverflow.com/users/8090', 'pm_score': 2, 'selected': False, 'text': '<p>Contrary to Patrick\'s answer, C++ has no <code>^^</code> operator for performing a short-circuiting exclusive or. If you think about it for a second, having a <code>^^</code> operator wouldn\'t make sense anyway: with exclusive or, the result always depends on both operands. However, Patrick\'s warning about non-<code>bool</code> "Boolean" types holds equally well when comparing <code>1 &amp; 2</code> to <code>1 &amp;&amp; 2</code>. One classic example of this is the Windows <a href="http://msdn.microsoft.com/en-us/library/ms644936.aspx" rel="nofollow noreferrer"><code>GetMessage()</code></a> function, which returns a tri-state <code>BOOL</code>: nonzero, <code>0</code>, or <code>-1</code>.</p>\n\n<p>Using <code>&amp;</code> instead of <code>&amp;&amp;</code> and <code>|</code> instead of <code>||</code> is not an uncommon typo, so if you are deliberately doing it, it deserves a comment saying why.</p>\n'}, {'answer_id': 13986306, 'author': 'Cheers and hth. - Alf', 'author_id': 464581, 'author_profile': 'https://Stackoverflow.com/users/464581', 'pm_score': 3, 'selected': False, 'text': '<h1>Disadvantages of the bitlevel operators.</h1>\n\n<p>You ask:</p>\n\n<blockquote>\n  <p>&ldquo;Is there any reason not to use the bitwise operators <code>&amp;</code>, <code>|</code>, and <code>^</code> for "bool" values in C++? &rdquo;</p>\n</blockquote>\n\n<p>Yes, the <strong>logical operators</strong>, that is the built-in high level boolean operators <code>!</code>, <code>&amp;&amp;</code> and <code>||</code>, offer the following advantages:</p>\n\n<ul>\n<li><p>Guaranteed <strong>conversion of arguments</strong> to <code>bool</code>, i.e. to <code>0</code> and <code>1</code> ordinal value.</p></li>\n<li><p>Guaranteed <strong>short circuit evaluation</strong> where expression evaluation stops as soon as the final result is known.<br>\nThis can be interpreted as a tree-value logic, with <em>True</em>, <em>False</em> and <em>Indeterminate</em>.</p></li>\n<li><p>Readable textual equivalents <code>not</code>, <code>and</code> and <code>or</code>, even if I don\'t use them myself.<br>\nAs reader Antimony notes in a comment also the bitlevel operators have alternative tokens, namely <code>bitand</code>, <code>bitor</code>, <code>xor</code> and <code>compl</code>, but in my opinion these are less readable than <code>and</code>, <code>or</code> and <code>not</code>.</p></li>\n</ul>\n\n<p>Simply put, each such advantage of the high level operators is a disadvantage of the bitlevel operators.</p>\n\n<p>In particular, since the bitwise operators lack argument conversion to 0/1 you get e.g. <code>1 &amp; 2</code> &rarr; <code>0</code>, while <code>1 &amp;&amp; 2</code> &rarr; <code>true</code>. Also <code>^</code>, bitwise exclusive or, can misbehave in this way. Regarded as boolean values 1 and 2 are the same, namely <code>true</code>, but regarded as bitpatterns they\'re different.</p>\n\n<p><hr></p>\n\n<h1>How to express logical <em>either/or</em> in C++.</h1>\n\n<p>You then provide a bit of background for the question,</p>\n\n<blockquote>\n  <p>&ldquo;I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression.&rdquo;</p>\n</blockquote>\n\n<p>Well, the bitwise operators have <strong>higher precedence</strong> than the logical operators. This means in particular that in a mixed expression such as</p>\n\n<pre><code>a &amp;&amp; b ^ c\n</code></pre>\n\n<p>you get the perhaps unexpected result <code>a &amp;&amp; (b ^ c)</code>.</p>\n\n<p>Instead write just</p>\n\n<pre><code>(a &amp;&amp; b) != c\n</code></pre>\n\n<p>expressing more concisely what you mean.</p>\n\n<p>For the multiple argument <em>either/or</em> there is no C++ operator that does the job. For example, if you write <code>a ^ b ^ c</code> than that is not an expression that says &ldquo;either <code>a</code>, <code>b</code> or <code>c</code> is true&ldquo;. Instead it says, &ldquo;An odd number of <code>a</code>, <code>b</code> and <code>c</code> are true&ldquo;, which might be 1 of them or all 3&hellip;</p>\n\n<p>To express the general either/or when <code>a</code>, <code>b</code> and <code>c</code> are of type <code>bool</code>, just write</p>\n\n<pre><code>(a + b + c) == 1\n</code></pre>\n\n<p>or, with non-<code>bool</code> arguments, convert them to <code>bool</code>:</p>\n\n<pre><code>(!!a + !!b + !!c) == 1\n</code></pre>\n\n<p><hr></p>\n\n<h1>Using <code>&amp;=</code> to accumulate boolean results.</h1>\n\n<p>You further elaborate,</p>\n\n<blockquote>\n  <p>&ldquo;I also need to accumulate Boolean values sometimes, and <code>&amp;=</code> and <code>|=?</code> can be quite useful.&rdquo;</p>\n</blockquote>\n\n<p>Well, this corresponds to checking whether respectively <em>all</em> or <em>any</em> condition is satisfied, and <strong>de Morgan&rsquo;s law</strong> tells you how to go from one to the other. I.e. you only need one of them. You could in principle use <code>*=</code> as a <code>&amp;&amp;=</code>-operator (for as good old George Boole discovered, logical AND can very easily be expressed as multiplication), but I think that that would perplex and perhaps mislead maintainers of the code.</p>\n\n<p>Consider also:</p>\n\n<pre><code>struct Bool\n{\n    bool    value;\n\n    void operator&amp;=( bool const v ) { value = value &amp;&amp; v; }\n    operator bool() const { return value; }\n};\n\n#include &lt;iostream&gt;\n\nint main()\n{\n    using namespace std;\n\n    Bool a  = {true};\n    a &amp;= true || false;\n    a &amp;= 1234;\n    cout &lt;&lt; boolalpha &lt;&lt; a &lt;&lt; endl;\n\n    bool b = {true};\n    b &amp;= true || false;\n    b &amp;= 1234;\n    cout &lt;&lt; boolalpha &lt;&lt; b &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Output with Visual C++ 11.0 and g++ 4.7.1:</p>\n\n<pre>\ntrue\nfalse\n</pre>\n\n<p>The reason for the difference in results is that the bitlevel <code>&amp;=</code> does not provide a conversion to <code>bool</code> of its right hand side argument.</p>\n\n<p>So, which of these results do you desire for your use of <code>&amp;=</code>?</p>\n\n<p>If the former, <code>true</code>, then better define an operator (e.g. as above) or named function, or use an explicit conversion of the right hand side expression, or write the update in full.</p>\n'}, {'answer_id': 50039597, 'author': 'Anoop Menon', 'author_id': 946836, 'author_profile': 'https://Stackoverflow.com/users/946836', 'pm_score': 1, 'selected': False, 'text': "<p>Using bitwise operations for bool helps save unnecessary branch prediction logic by the processor, resulting from a 'cmp' instruction brought in by logical operations.</p>\n\n<p>Replacing the logical with bitwise operations (where all operands are bool) generates more efficient code offering the same result. The efficiency ideally should outweigh all the short-circuit benefits that can be leveraged in the ordering using logical operations.</p>\n\n<p>This can make code a bit un-readable albeit the programmer should comment it with reasons why it was done so. </p>\n"}]
['https://Stackoverflow.com/questions/24542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1891/']