OStack程序员社区-中国程序员成长平台

标题: c# -++i 运算符在 C# 和 C++ 中的区别 [打印本页]

作者: 菜鸟教程小白    时间: 2022-8-3 00:17
标题: c# -++i 运算符在 C# 和 C++ 中的区别

我用 C++ 和 C# 编写了以下代码

 int i=0;
 ++i = 11;

在这个 C# 编译器带来错误之后
The left-hand side of an assignment must be a variable, property or indexer

但是 C++ 编译器生成这段代码没有错误,我得到了一个结果 11对于 i 的值.这种差异的原因是什么?



Best Answer-推荐答案


不同的是预增运算符是左值在 C++ 中,而不是在 C# 中。
在 C++ 中 ++i返回对递增变量的引用。在 C# 中 ++i返回变量 i 的递增值。
所以在这种情况下 ++i左值在 C++ 和 中右值 在 C# 中。

来自关于前缀增量运算符的 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.



附言后缀增量运算符 i++ 在 C# 和 C++ 中都不是左值,因此这行代码在两种语言中都会带来错误。
 int i=0;
 i++ = 11;

关于c# -++i 运算符在 C# 和 C++ 中的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9516926/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4