N
N
nazarovdaniil2014-10-10 22:12:56
C++ / C#
nazarovdaniil, 2014-10-10 22:12:56

Why as a result of program execution j=0 ?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
int j = 0;
for (int i = 0; i < 10; i++)
{
j = j++;
}
Console.WriteLine("j="+j);
Console.ReadKey();
}
}
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya Glebov, 2014-10-10
@IljaGlebov

The result of a postfix increment is the value of the argument before adding 1.
That is, the code j = j++ can be represented as follows

int tmp = j;
j = j + 1;
j = temp;

If you look at IL, then in j = j++ there will be such code
IL_0006: ldloc.0 // В стек кладем значение j (оно у нас == 0)
IL_0007: dup     // Дублируем в стеке значение j  
IL_0008: ldc.i4.1 // Кладем второй аргумент инкремента (он == 1)
IL_0009: add      // Складываем два верних значения, результат кладем в стек
IL_000a: stloc.0  // Сохраняем в j результат сложения
IL_000b: stloc.0  // Сохраняем в j 0, который получился при dup

I drew what happens on the stack. The opcode dup is interesting here, which just does int tmp = j;
d278f75397094999b1cb5f60e8fe6a6d.png

J
jcmvbkbc, 2014-10-10
@jcmvbkbc

Therefore, choose one thing, and instead of j = j++; write either j = j + 1; or just j++;

M
mamkaololosha, 2014-10-10
@mamkaololosha

This is a systematic error of increments. Different compilers handle it differently.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question