Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For i = 0, why is (i += i++) equal to 0?

Tags:

c#

.net

Take the following code (usable as a Console Application):

static void Main(string[] args)
{
    int i = 0;
    i += i++;
    Console.WriteLine(i);
    Console.ReadLine();
}

The result of i is 0. I expected 2 (as some of my colleagues did). Probably the compiler creates some sort of structure that results in i being zero.

The reason I expected 2 is that, in my line of thought, the right hand statement would be evaluated first, incrementing i with 1. Than it is added to i. Since i is already 1, it is adding 1 to 1. So 1 + 1 = 2. Obviously this is not what's happening.

Can you explain what the compiler does or what happens at runtime? Why is the result zero?

Some-sort-of-disclaimer: I'm absolutely aware you won't (and probably shouldn't) use this code. I know I never will. Nevertheless, I find it is interesting to know why it acts in such a way and what is happening exactly.

like image 952
Peter Avatar asked Nov 22 '12 16:11

Peter


People also ask

Is zero less than or equal to zero?

4 Answers. Show activity on this post. No zero is not less then zero, i <= 0 becomes 1 because zero is less than or equal to zero.

What is the meaning of i += 1?

i+=i means the i now adds its current value to its self so let's say i equals 10 using this += expression the value of i will now equal 20 because you just added 10 to its self. i+=1 does the same as i=i+1 there both incrementing the current value of i by 1. 3rd January 2020, 3:15 AM.

What is i 1 in C programming?

While the expression i-1 always execute the operation before to use the result (it behaves as a prefixed decrement operator), using increment or decrement operators as prefix the action, increment or decrement, is performed first then the result is used.


17 Answers

This:

int i = 0;
i += i++

Can be seen as you doing (the following is a gross oversimplification):

int i = 0;
i = i + i; // i=0 because the ++ is a postfix operator and hasn't been executed
i + 1; // Note that you are discarding the calculation result

What actually happens is more involved than that - take a look at MSDN, 7.5.9 Postfix increment and decrement operators:

The run-time processing of a postfix increment or decrement operation of the form x++ or x-- consists of the following steps:

  • If x is classified as a variable:

    • x is evaluated to produce the variable.
    • The value of x is saved.
    • The selected operator is invoked with the saved value of x as its argument.
    • The value returned by the operator is stored in the location given by the evaluation of x.
    • The saved value of x becomes the result of the operation.

Note that due to order of precedence, the postfix ++ occurs before +=, but the result ends up being unused (as the previous value of i is used).


A more thorough decomposition of i += i++ to the parts it is made of requires one to know that both += and ++ are not atomic (that is, neither one is a single operation), even if they look like they are. The way these are implemented involve temporary variables, copies of i before the operations take place - one for each operation. (I will use the names iAdd and iAssign for the temporary variables used for ++ and += respectively).

So, a closer approximation to what is happening would be:

int i = 0;
int iAdd = i; // Copy of the current value of i, for ++
int iAssign = i; // Copy of the current value of i, for +=

i = i + 1; // i++ - Happens before += due to order of precedence
i = iAdd + iAssign;
like image 194
Oded Avatar answered Oct 14 '22 16:10

Oded


What C# is doing, and the "why" of the confusion

I also expected the value to be 1... but some exploration on that matter did clarify some points.

Cosider the following methods:

    static int SetSum(ref int a, int b) { return a += b; }

    static int Inc(ref int a) { return a++; }

I expected that i += i++ to be the same as SetSum(ref i, Inc(ref i)). The value of i after this statement is 1:

int i = 0;
SetSum(ref i, Inc(ref i));
Console.WriteLine(i); // i is 1

But then I came to another conclusion... i += i++ is actually the same as i = i + i++... so I have created another similar example, using these functions:

    static int Sum(int a, int b) { return a + b; }

    static int Set(ref int a, int b) { return a = b; }

After calling this Set(ref i, Sum(i, Inc(ref i))) the value of i is 0:

int i = 0;
Set(ref i, Sum(i, Inc(ref i)));
Console.WriteLine(i); // i is 0

This not only explains what C# is doing... but also why a lot of people got confused with it... including me.

like image 27
Miguel Angelo Avatar answered Oct 14 '22 17:10

Miguel Angelo


int i = 0;
i += i++;

is evaluated as follows:

Stack<int> stack = new Stack<int>();
int i;

// int i = 0;
stack.Push(0);                   // push 0
i = stack.Pop();                 // pop 0 --> i == 0

// i += i++;
stack.Push(i);                   // push 0
stack.Push(i);                   // push 0
stack.Push(i);                   // push 0
stack.Push(1);                   // push 1
i = stack.Pop() + stack.Pop();   // pop 0 and 1 --> i == 1
i = stack.Pop() + stack.Pop();   // pop 0 and 0 --> i == 0

i.e. i is changed twice: once by the i++ expression and once by the += statement.

But the operands of the += statement are

  • the value i before the evaluation of i++ (left-hand side of +=) and
  • the value i before the evaluation of i++ (right-hand side of +=).
like image 43
dtb Avatar answered Oct 14 '22 17:10

dtb


First, i++ returns 0. Then i is incremented by 1. Lastly i is set to the initial value of i which is 0 plus the value i++ returned, which is zero too. 0 + 0 = 0.

like image 45
Jong Avatar answered Oct 14 '22 17:10

Jong


This is simply left to right, bottom-up evaluation of the abstract syntax tree. Conceptually, the expression's tree is walked from top down, but the evaluation unfolds as the recursion pops back up the tree from the bottom.

// source code
i += i++;

// abstract syntax tree

     +=
    /  \
   i    ++ (post)
         \
         i

Evaluation begins by considering the root node +=. That is the major constituent of the expression. The left operand of += must be evaluated to determine the place where we store the variable, and to obtain the prior value which is zero. Next, the right side must be evaluated.

The right side is a post-incrementing ++ operator. It has one operand, i which is evaluated both as a source of a value, and as a place where a value is to be stored. The operator evaluates i, finding 0, and consequently stores a 1 into that location. It returns the prior value, 0, in accordance with its semantics of returning the prior value.

Now control is back to the += operator. It now has all the info to complete its operation. It knows the place where to store the result (the storage location of i) as well as the prior value, and it has the value to added to the prior value, namely 0. So, i ends up with zero.

Like Java, C# has sanitized a very asinine aspect of the C language by fixing the order of evaluation. Left-to-right, bottom-up: the most obvious order that is likely to be expected by coders.

like image 39
Kaz Avatar answered Oct 14 '22 17:10

Kaz


Because i++ first returns the value, then increments it. But after i is set to 1, you set it back to 0.

like image 32
Yuriy Faktorovich Avatar answered Oct 14 '22 17:10

Yuriy Faktorovich


The post-increment method looks something like this

int ++(ref int i)
{
    int c = i;
    i = i + 1;
    return c;
}

So basically when you call i++, i is increment but the original value is returned in your case it's 0 being returned.

like image 40
Ash Burlaczenko Avatar answered Oct 14 '22 16:10

Ash Burlaczenko


Simple answer

int i = 0;
i += i++;
// Translates to:
i = i + 0; // because post increment returns the current value 0 of i
// Before the above operation is set, i will be incremented to 1
// Now i gets set after the increment,
// so the original returned value of i will be taken.
i = 0;
like image 28
Praveen Kumar Purushothaman Avatar answered Oct 14 '22 15:10

Praveen Kumar Purushothaman


i++ means: return the value of i THEN increment it.

i += i++ means: Take the current value of i. Add the result of i++.

Now, let's add in i = 0 as a starting condition. i += i++ is now evaluated like this:

  1. What's the current value of i? It is 0. Store it so we can add the result of i++ to it.
  2. Evaluate i++ (evaluates to 0 because that's the current value of i)
  3. Load the stored value and add the result of step 2 to it. (add 0 to 0)

Note: At the end of step 2, the value of i is actually 1. However, in step 3, you discard it by loading the value of i before it was incremented.

As opposed to i++, ++i returns the incremented value.

Therefore, i+= ++i would give you 1.

like image 34
Carl Avatar answered Oct 14 '22 17:10

Carl


The post fix increment operator, ++, gives the variable a value in the expression and then do the increment you assigned returned zero (0) value to i again that overwrites the incremented one (1), so you are getting zero. You can read more about increment operator in ++ Operator (MSDN).

like image 41
Adil Avatar answered Oct 14 '22 15:10

Adil


i += i++; will equal zero, because it does the ++ afterwards.

i += ++i; will do it before

like image 34
Wes Cossick Avatar answered Oct 14 '22 17:10

Wes Cossick


The ++ postfix evaluates i before incrementing it, and += only evaluates i once.

Therefore, 0 + 0 = 0, as i is evaluated and used before it is incremented, as the postfix format of ++ is used. To get i incremented first, use the prefix form (++i).

(Also, just a note: you should only get 1, as 0 + (0 + 1) = 1)

References: http://msdn.microsoft.com/en-us/library/sa7629ew.aspx (+=)
http://msdn.microsoft.com/en-us/library/36x43w8w.aspx (++)

like image 37
Nate Koppenhaver Avatar answered Oct 14 '22 17:10

Nate Koppenhaver


The steps in calculation are:

  1. int i=0 //Initialized to 0
  2. i+=i++ //Equation
  3. i=i+i++ //after simplifying the equation by compiler
  4. i=0+i++ //i value substitution
  5. i=0+0 //i++ is 0 as explained below
  6. i=0 //Final result i=0

Here, initially the value of i is 0. WKT, i++ is nothing but: first use the i value and then increment the i value by 1. So it uses the i value, 0, while calculating i++ and then increments it by 1. So it results in a value of 0.

like image 30
Suresh M Avatar answered Oct 14 '22 15:10

Suresh M


Be very careful: read the C FAQ: what you're trying to do (mixing assignement and ++ of the same variable) is not only unspecified, but it is also undefined (meaning that the compiler may do anything when evaluating!, not only giving "reasonnable" results).

Please read, section 3. The whole section is well worth a read! Especially 3.9, which explains the implication of unspecified. Section 3.3 gives you a quick summary of what you can, and cannot do, with "i++" and the like.

Depending on the compilers internals, you may get 0, or 2, or 1, or even anything else! And as it is undefined, it's OK for them to do so.

like image 31
Olivier Dulac Avatar answered Oct 14 '22 17:10

Olivier Dulac


A good mnemonic I always remember about this is the following:

If ++ stands after the expression, it returns the value it was before. So the following code

int a = 1;
int b = a++;

is 1, because a was 1 before it got increased by the ++ standing after a. People call this postfix notation. There is also a prefix notation, where things are exactly the opposite: if ++ stands before, the expression returns the value that it is after the operation:

int a = 1;
int b = ++a;

b is two in here.

So for your code, this means

int i = 0;
i += (i++);

i++ returns 0 (as described above), so 0 + 0 = 0.

i += (++i); // Here 'i' would become two

Scott Meyers describes the difference between those two notations in "Effective C++ programming". Internally, i++ (postfix) remembers the value i was, and calls the prefix-notation (++i) and returns the old value, i. This is why you should allways use ++i in for loops (although I think all modern compilers are translating i++ to ++i in for loops).

like image 41
Carsten Avatar answered Oct 14 '22 15:10

Carsten


The only answer to your question which is correct is: Because it is undefined.

Ok, before you all burn me..

You all answered why i+=i++ is ok and logical to result in i=0.

I was tempted to down vote each and every 1 of your answers but the reputation hit I calculated would be too high..

Why I am so mad at you people? not because of what your answers explains..
I mean, every answer I read had made a remarkable effort to explain the impossible, I Applause!

But what is the result?? is it intuitive result - is it acceptable result??

Each one of you seen the "naked king" and somehow accepted it as a rational king.

You are all WRONG!

i+=i++; result in 0 is undefined.

a bug in the language evaluation mechanism if you will.. or even worse! a bug in design.

want a proof? of course you want!

int t=0; int i=0; t+=i++; //t=0; i=1

Now this... is intuitive result! because we first evaluated t assigned it with a value and only after evaluation and assignment we had the post operation happening - rational isn't it?

is it rational that: i=i++ and i=i yield the same result for i?

while t=i++ and t=i have different results for i.

The post operation is something that should happen after the statement evaluation.
Therefore:

int i=0;
i+=i++;

Should be the same if we wrote:

int i=0;
i = i + i ++;

and therefore the same as:

int i=0;
i= i + i;
i ++;

and therefore the same as:

int i=0;
i = i + i;
i = i + 1;

Any result which is not 1 indicate a bug in the complier or a bug in the language design if we go with rational thinking - however MSDN and many other sources tells us "hey - this is undefined!"

Now, before I continue, even this set of examples I gave is not supported or acknowledged by anyone.. However this is what according to intuitive and rational way should have been the result.

The coder should have no knowledge of how the assembly is being written or translated!

If it is written in a manner that will not respect the language definitions - it is a bug!

And to finish I copied this from Wikipedia, Increment and decrement operators :
Since the increment/decrement operator modifies its operand, use of such an operand more than once within the same expression can produce undefined results. For example, in expressions such as x − ++x, it is not clear in what sequence the subtraction and increment operators should be performed. Situations like this are made even worse when optimizations are applied by the compiler, which could result in the order of execution of the operations to be different than what the programmer intended.

And therefore.

The correct answer is that this SHOULD NOT BE USED! (as it is UNDEFINED!)

Yes.. - It has unpredictable results even if C# complier is trying to normalize it somehow.

I did not find any documentation of C# describing the behavior all of you documented as a normal or well defined behavior of the language. What I did find is the exact opposite!

[copied from MSDN documentation for Postfix Increment and Decrement Operators: ++ and --]

When a postfix operator is applied to a function argument, the value of the argument is not guaranteed to be incremented or decremented before it is passed to the function. See section 1.9.17 in the C++ standard for more information.

Notice those words not guaranteed...

Forgive me if that answer seems arrogant - I am not an arrogant person. I just consider that thousands of people come here to learn and the answers I read will mislead them and will harm their logic and understanding of the subject.

like image 24
G.Y Avatar answered Oct 14 '22 17:10

G.Y


The ++ operator after the variable makes it a postfix increment. The incrementing happens after everything else in the statement, the adding and assignment. If instead, you put the ++ before the variable, it would happen before i's value was evaluated, and give you the expected answer.

like image 24
KeithS Avatar answered Oct 14 '22 17:10

KeithS