I just read the C reference about prefix increment operator and realized that the result of prefix increment operator are not lvalue, but it's surprising that it is lvalue in C++. After that I read this answer which explaining why it's a lvalue, but I don't understand it:
(Line 3): ["] it appears that it is so you can take its address or assign to a reference. [."]
and an example follows:
int i; extern void f (int* p); f (&++i); /* Would be illegal C, but C programmers havent missed this feature */ ...
So what's the merit of allowing this? Is the only purpose of this that incrementing i
in global region is illegal? If this is the only reason I would consider this be a remedy for a defect in C that cannot/hard to be resolved, or the program should probably be rewritten for the sake of readability, right?
btw I don't understand why lvalue is also called "locator value", I've read this - line 4 but locator is vague for me. What's a locator, is it a pointer something?
EDIT: For the sake of your precious time reading about wth is locator value, here is my homemade backronym:
don't blame me if anything gone wrong.
The only difference is the order of operations between the increment of the variable and the value the operator returns. So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.
Prefix Increment and Decrement Operators: ++ and -- The prefix increment operator (++) adds one to its operand; this incremented value is the result of the expression. The operand must be an l-value not of type const . The result is an l-value of the same type as the operand.
Postfix decrement operator means the expression is evaluated first using the original value of the variable and then the variable is decremented(decreased). Prefix increment operator means the variable is incremented first and then the expression is evaluated using the new value of the variable.
Preincrement and Postincrement in C are the two ways to use the increment operator. In Pre-Increment, the operator sign (++) comes before the variable. It increments the value of a variable before assigning it to another variable. In Post-Increment, the operator sign (++) comes after the variable.
In C++, prefix ++
giving lvalue is actually very natural.
Because C++ has operator overloading. For most iterators of potentially complicated type, the prefix ++
returns the lvalue of the iterator itself.
Thus for generic programming, it would be inconvenient to make fundamental type a special case.
For example;
auto &iter = ++old_iter;
wouldn't work if prefix increment of pointer gives an rvalue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With