Początki w C# (nie rozumiem czemu program działa w taki sposób)

0

Dobry wieczór.

Mam proszę ja Was taki krótki programik

static void Main(string[] args)
{
int x = 0, y;
y = x++ * 2;
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadKey();

Dlaczego w tym wypadku na konsoli x=1 a y=0?
Nie powinno być x=0 a y z racji inkrementacji x y=2?
Proszę mi to wytłumaczyć.

0

y = (x zwiększ go JAKBY później, ale nie teraz o 1) * 2

y = 0 * 2

y = 0

x zwiększony później = 1

0

Czyli to tak działa. Teraz rozumiem. Dziękuję.

0

Operator postinkrementacji x++ w wyrażeniu używa aktualnej wartości x czyli zero(dlatego y=0, bo 0 * 2 = 0), a inkrementuje pózniej; dlatego po trzeciej linijce programu x = 1.

0

Tutaj jest jak naprawdę działa ++i oraz i++

Eric Lippert - What is the difference between i++ and ++i?

It is not obvious what the answer to either question is, but it is actually quite simple once you see it. Let me spell out for you precisely what x++ and ++x do for a variable x.

For the prefix form:

x is evaluated to produce the variable
The value of the variable is copied to a temporary location
The temporary value is incremented to produce a new value (not overwriting the temporary!)
The new value is stored in the variable
The result of the operation is the new value (i.e. the incremented value of the temporary)

For the postfix form:

x is evaluated to produce the variable
The value of the variable is copied to a temporary location
The temporary value is incremented to produce a new value (not overwriting the temporary!)
The new value is stored in the variable
The result of the operation is the value of the temporary

First, the order of events in time is exactly the same in both cases. Again, it is absolutely not the case that the order of events in time changes between prefix and postfix. It is entirely false to say that the evaluation happens before other evaluations or after other evaluations. The evaluations happen in exactly the same order in both cases as you can see by steps 1 through 4 being identical. The only difference is the last step - whether the result is the value of the temporary, or the new, incremented value.

1 użytkowników online, w tym zalogowanych: 0, gości: 1