Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 606
shift66 Avatar asked Mar 01 '12 13:03

shift66


People also ask

What is i ++ and ++ i in C?

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.

What is the difference between -- I and I --?

--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.

What is the difference between i ++ and i += 1?

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.

What is better i ++ or ++ i?

++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.


2 Answers

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;
like image 58
Chuck Norris Avatar answered Oct 19 '22 22:10

Chuck Norris


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.

like image 39
fredoverflow Avatar answered Oct 19 '22 23:10

fredoverflow