Why don't C++ compilers optimize this conditional boolean assignment as an unconditional assignment?
<p>Consider the following function:</p>

<pre><code>void func(bool&amp; flag)
{
    if(!flag) flag=true;
}
</code></pre>

<p>It seems to me that if flag has a valid boolean value, this would be equivalent to unconditional setting it to <code>true</code>, like this:</p>

<pre><code>void func(bool&amp; flag)
{
    flag=true;
}
</code></pre>

<p>Yet neither gcc nor clang optimize it this way — both generate the following at <code>-O3</code> optimization level:</p>

<pre><code>_Z4funcRb:
.LFB0:
    .cfi_startproc
    cmp BYTE PTR [rdi], 0
    jne .L1
    mov BYTE PTR [rdi], 1
.L1:
    rep ret
</code></pre>

<p>My question is: is it just that the code is too special-case to care to optimize, or are there any good reasons why such optimization would be undesired, given that <code>flag</code> is not a reference to <code>volatile</code>? It seems the only reason which might be is that <code>flag</code> could somehow have a non-<code>true</code>-or-<code>false</code> value without undefined behavior at the point of reading it, but I'm not sure whether this is possible.</p>