Created
April 12, 2016 23:53
-
-
Save jdee/d4bcae12f482c2877f849fb2ea89e62c to your computer and use it in GitHub Desktop.
Hello, Operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int i = 0; | |
++ ++ i; // no problem | |
i ++ ++; // doesn't compile | |
/* | |
* It has to do with how these operators work and in particular their return types. The prefix operator returns | |
* the value after modification. The postfix operator returns the value before modification. But how does it do | |
* that? These operators date back to C at least. It's not some background task that happens after the operator | |
* finishes. The prefix operator returns a reference to the same thing (int, object, etc.). The postfix operator | |
* returns a temporary value. It stores the value in a separate location, modifies the value at the original | |
* location and then returns the stored value as a temporary. Hence the return value of the postfix operator | |
* can't be modified. It's not an lvalue (a value that can appear on the left-hand side of an assignment). | |
* The prefix operator gives you back a reference to the same modified thing without making a copy. This reference | |
* can continue to be modified. | |
* | |
* The signatures of these operators: | |
*/ | |
int& operator++(); // prefix | |
int operator++(int); // postfix |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment