Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Any compiler worth its salt will generate exactly the same machine-language sequence for both constructs for any built-in type (<code>int</code>, <code>float</code>, etc) as long as the statement really is as simple as <code>x = x + a;</code> <em>and optimization is enabled</em>. (Notably, GCC's <code>-O0</code>, which is the default mode, performs <em>anti-optimizations</em>, such as inserting completely unnecessary stores to memory, in order to ensure that debuggers can always find variable values.)</p> <p>If the statement is more complicated, though, they might be different. Suppose <code>f</code> is a function that returns a pointer, then</p> <pre><code>*f() += a; </code></pre> <p>calls <code>f</code> only once, whereas</p> <pre><code>*f() = *f() + a; </code></pre> <p>calls it twice. If <code>f</code> has side effects, one of the two will be wrong (probably the latter). Even if <code>f</code> doesn't have side effects, the compiler may not be able to eliminate the second call, so the latter may indeed be slower.</p> <p>And since we're talking about C++ here, the situation is entirely different for class types that overload <code>operator+</code> and <code>operator+=</code>. If <code>x</code> is such a type, then -- before optimization -- <code>x += a</code> translates to</p> <pre><code>x.operator+=(a); </code></pre> <p>whereas <code>x = x + a</code> translates to</p> <pre><code>auto TEMP(x.operator+(a)); x.operator=(TEMP); </code></pre> <p>Now, if the class is properly written <em>and</em> the compiler's optimizer is good enough, both will wind up generating the same machine language, but it's not a sure thing like it is for built-in types. This is probably what Stroustrup is thinking of when he encourages use of <code>+=</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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