++i operator difference in C# and C++

这一生的挚爱 提交于 2019-12-10 12:43:05

问题


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?


回答1:


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;



回答2:


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.




回答3:


C# and C++ are 2 totally different languages and concepts. They only share the name because their syntax is based on C. So actually "why this works on C# but not on C++" makes no sense as a question. It's the same as saying why a table is called "table" in English, but "mesa" in Spanish. Because it was decided to be that way.

C# simply does not allow such syntax.

In C++ you're allowed to: first ++i is computed, which makes i = 1, and then 11 is assigned to i, which makes i = 11.




回答4:


the semantics are very different. In c++ the semantics are that you assign the value 11 to the storage location identified by i. In C# the semantics are equal to the semantics of the below statement

1=11

That is it's equal to trying to assign the value 11 to the value 1 which the C# compiler does not allow. (Fortran compilers actually do allow this and that can create hellish debugging scenarios)



来源:https://stackoverflow.com/questions/9516926/i-operator-difference-in-c-sharp-and-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!