I have the following code written in both C++ and C#
int i=0;
++i = 11;
After this C# compiler brings an error
The left-hand side of an assignment must be a variable, property or indexer
But C++ compiler generate this code with no error and I got a result 11
for value of i
. What's the reason of this difference?
In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.
--i decrements i by 1 then gives you the value of i (4). i-- gives you the value of i (5) then decrements it by 1. Both will give you the same result in a for loop.
These two are exactly the same. It's just two different ways of writing the same thing. i++ is just a shortcut for i += 1 , which itself is a shortcut for i = i + 1 . These all do the same thing, and it's just a question of how explicit you want to be.
++i is sometimes faster than, and is never slower than, i++. For intrinsic types like int, it doesn't matter: ++i and i++ are the same speed. For class types like iterators or the previous FAQ's Number class, ++i very well might be faster than i++ since the latter might make a copy of the this object.
The difference is that pre-increment operator is lvalue in C++, and isn't in C#.
In C++ ++i
returns a reference to the incremented variable. In C# ++i
returns the incremented value of variable i.
So in this case ++i
is lvalue in C++ and rvalue in C#.
From C++ specification about prefix increment operator
The type of the operand shall be an arithmetic type or a pointer to a completely-defined object type. The value is the new value of the operand; it is an lvalue.
P.S. postfix increment operator i++ isn't lvalue in both C# and C++, so this lines of code will bring error in both languages.
int i=0;
i++ = 11;
Note that ++i = 11
invokes undefined in C++03 because you are modifying i
twice without an intervening sequence point. It is well defined in C++11, however: first the increment, then the assignment.
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