Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's many similar posts at Stackoverflow:</p> <ul> <li><a href="https://stackoverflow.com/questions/484462/difference-between-i-and-i-in-a-loop">Difference between i++ and ++i in a loop?</a></li> <li><a href="https://stackoverflow.com/questions/467322/is-there-any-performance-difference-between-i-and-i-in-c">Is there any performance difference between ++i and i++ in C#?</a></li> <li><a href="https://stackoverflow.com/questions/24886/is-there-a-performance-difference-between-i-and-i-in-c">Is there a performance difference between i++ and ++i in C?</a></li> </ul> <p>However, it seems your question is more generic because it's not specific to any language or compiler. Most of the above questions deal with a specific language/compiler.</p> <p>Here's a rundown:</p> <ul> <li>if we are talking about C/C++/Java (probably C# too) and a modern compiler: <ul> <li>if <code>i</code> is an integer (<code>const int</code>, <code>int</code>, etc.): <ul> <li>then the compiler will basically replace <code>i++</code> with <code>++i</code>, because they are semantically identical and so it doesn't change the output. this can be verified by checking the generated code / bytecode (for Java, I use the <a href="http://www.ej-technologies.com/products/jclasslib/overview.html" rel="nofollow noreferrer">jclasslib bytecode viewer</a>).</li> </ul></li> <li>else:</li> </ul></li> <li>else: <ul> <li>all bets are off, because the compiler cannot guarantee that they are semantically identical, so it does not try to optimize.</li> </ul></li> </ul> <p>So if you have a class in C++ that overrides the postfix and prefix operators (like <code>std::iterator</code>), this optimization is rarely, if ever, done.</p> <p>In summary:</p> <ul> <li>Mean what you say, and say what you mean. For the increment part of <code>for</code> loops, you almost always want the prefix version (i.e., <code>++i</code>).</li> <li>The compiler switcheroo between <code>++i</code> and <code>i++</code> can't always be done, but it'll try to do it for you if it can.</li> </ul>
    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. This table or related slice is empty.
    1. This table or related slice is empty.
    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