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?
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;