Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are pre- and post- inc/decrement operators implemented separately?
    text
    copied!<p>I am trying to find the rationale behind having the re- and post- versions of the increment and decrement operators overloadable separately.<br> In my mind, and in every implementation I have ever seen of these operators for any type of class, these are the same operator (=do the same thing) and just differ in when it is called.<br> It would seem much more logical to me that the designers of C++ would have had <em>one</em> <code>++</code> operator, and the compiler would call it as needed, either before or after reading the value (or, more likely, at the previous or next sequence point, which I think is equivalent)</p> <p>So, <strong>the question is</strong>: Does anyone have an example of a case/class where these might <em>not</em> be implemented the same? Or does anyone know/guess the rationale behind this design choice?</p> <hr> <p>For those that prefer to look at code than read text in a question, here is the summary:</p> <p>For what type <code>T</code> (a user defined class representing anything you want) would it make sense for the following 2 lines to <em>not</em> have the same side effects:</p> <pre><code>T v; v++; ++v; </code></pre> <hr> <p><strong>EDIT</strong><br> To quote @Simple's comment below, which I hope clarifys the question:</p> <blockquote> <p>Why post-increment (overloading) is in the language if the compiler can just do a copy itself and do the pre-increment</p> </blockquote> <hr> <p><strong>EDIT 2</strong><br> Since the question is apparently unclear to many, here is another explanation:</p> <p>Consider the following two lines:</p> <pre><code>b = a++; b = ++a; </code></pre> <p>If it was one operator (for the sake of argument, I will call the operator +a+), the first line would be translated by the compiler into</p> <pre><code>b = a; +a+; </code></pre> <p>and the second into</p> <pre><code>+a+; b = a; </code></pre>
 

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