[英]++i operator difference in C# and C++
I have the following code written in both C++ and C# 我有以下用C ++和C#编写的代码
int i=0;
++i = 11;
After this C# compiler brings an error 在此C#编译器带来错误之后
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
. 但C ++编译器生成此代码时没有错误,我得到了
i
值为11
的结果。 What's the reason of this difference? 这种差异的原因是什么?
The difference is that pre-increment operator is lvalue in C++, and isn't in C#. 不同之处在于,预增量运算符在C ++中是左值 ,而不在C#中。
In C++ ++i
returns a reference to the incremented variable. 在C ++
++i
返回对递增变量的引用。 In C# ++i
returns the incremented value of variable i. 在C#
++i
返回变量i的递增值。
So in this case ++i
is lvalue in C++ and rvalue in C#. 所以在这种情况下,
++i
在C ++中是左 值,在C#中是右值 。
From C++ specification about prefix increment operator 从C ++规范关于前缀增量运算符
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 .
这是一个左值 。
PS postfix increment operator i++ isn't lvalue in both C# and C++, so this lines of code will bring error in both languages. PS后缀增量运算符i ++在C#和C ++中都不是左值,因此这行代码会在两种语言中带来错误。
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. 注意,
++i = 11
所调用未定义在C ++ 03因为要修改i
没有插入序列点的两倍。 It is well defined in C++11, however: first the increment, then the assignment. 它在C ++ 11中有很好的定义,但是:首先是增量,然后是赋值。
C# and C++ are 2 totally different languages and concepts. C#和C ++是两种完全不同的语言和概念。 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.
他们只共享名称,因为他们的语法是基于C.所以实际上“为什么这适用于C#但不适用于C ++”作为一个问题毫无意义。 It's the same as saying why a table is called "table" in English, but "mesa" in Spanish.
这就像说为什么一张表用英语称为“表”,而用西班牙语称为“mesa”。 Because it was decided to be that way.
因为决定那样。
C# simply does not allow such syntax. C#根本不允许这样的语法。
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
. 在C ++中,你被允许:首先计算
++i
,使得i = 1
,然后将11分配给i
,这使得i = 11
。
the semantics are very different. 语义是非常不同的。 In c++ the semantics are that you assign the value 11 to the storage location identified by i.
在c ++中,语义是您将值11分配给i标识的存储位置。 In C# the semantics are equal to the semantics of the below statement
在C#中,语义等于以下语句的语义
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. 这就等于尝试将值11分配给C#编译器不允许的值1。 (Fortran compilers actually do allow this and that can create hellish debugging scenarios)
(Fortran编译器实际上允许这样做,这可能会产生地狱般的调试方案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.